Small knowledge, big challenge! This article is part of the “Programmer’s Essentials

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Graduated for many years, although the university major is information security, at the time of university studied various encryption algorithms, but no in the security industry after graduation, has been playing games, doing web development, using encryption opportunities at work is not much, but encryption does have also been around, such as our game communication protocol is inevitable to encrypt data, Otherwise, unpack casually a bit dangerous, brush protocol harassment server. Today to talk about the commonly used encryption algorithm, the next server also want to choose a encryption algorithm, you help me choose a?

1. Classification of encryption algorithms

Encryption algorithms are classified into decryptable algorithms and undecryptable algorithms

For example, MD5, SHA, and HMAC encryption algorithms are non-reversible encryption methods that cannot be decrypted. They are called one-way encryption algorithms and are commonly used to verify data security.

BASE64 is strictly an encoding format rather than an encryption algorithm MD5(Message Digest Algorithm 5) SHA(Secure Hash Algorithm)

Encryption algorithms are generally classified into symmetric encryption and asymmetric encryption

For example, the encryption algorithms based on [symmetric key] include DES, 3DES (TripleDES), AES, RC2, RC4, RC5, and Blowfish

Asymmetric encryption: RSA, ECC (for mobile devices), Diffie-Hellman, El Gamal, DSA (for digital signature)

2. Implementation of encryption algorithm

1. BASE64

Base64 is used to encode data transmitted in the network. It belongs to the encoding format strictly. There are 64 characters corresponding encoding, and Base64 is to encode content in accordance with this format. It can encode and decode data, which is reversible and has low security. However, it can also be used as the most basic and simplest encryption algorithm for weak encryption requirements.

Base64 can be implemented using native classes in the JDk, Bouncy Castle (BC) or Commons Codec (CC)

Here’s an example:

import org.apache.commons.codec.binary.Base64;
​
public class Aain {
    public static byte[] encode2Base64(byte[] bytes) {
        byte[] bts = Base64.encodeBase64(bytes);
        return bts;
    }
    public static byte[] decode2Base64(String str) {
        byte[] bts = Base64.decodeBase64(str);
        returnbts; }}Copy the code

2. MD5

MD5 (message-digest algorithm 5), used to ensure complete and consistent transmission of information. MD5 has been widely implemented in mainstream programming languages. Computing data (such as Chinese characters) into another fixed length value is the basis of the hashing algorithm. The predecessors of MD5 are MD2, MD3 and MD4. Widely used in encryption and decryption technology, often used for file verification. No matter how big the file is, a unique MD5 value can be generated after MD5.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
​
public class Aain {
    public static String md5(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            return new String(digest.digest(str.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
​
    public static void main(String[] args) {
        System.out.println(md5("ddddddddddddd")); }}Copy the code

The MD5 command is supported in Linux

Calculate the MD5 value of the file md5sum final.nnetCopy the code

3.SHA

The Secure Hash Algorithm applies to the Digital Signature Algorithm DSA defined in the Digital Signature Standard (DSS). For messages less than 2^64 bits in length, SHA1 produces a 160-bit message digest. The algorithm has been developed and improved by encryption experts for many years and is widely used. Ideas of the algorithm is to receive a Duan Mingwen, then in an irreversible way to convert it to a (usually less) ciphertext, can also be a simple understanding to take a series of input code (called mapping or information), and put them into shorter length, the output sequence of digits fixed the hash value (also known as the information or message authentication code) process. The hash function value is kind of a fingerprint or a digest of the plaintext, so a digital signature of the hash value can be treated as a digital signature of the plaintext.

import java.math.BigInteger;
import java.security.MessageDigest;
​
public class Aain {
    public static final String  KEY_SHA = "SHA";
​
​
    public static void sha(String inputStr) {
        byte[] inputData = inputStr.getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA);
            messageDigest.update(inputData);
            BigInteger sha = new BigInteger(messageDigest.digest());
            System.out.println("After SHA encryption :" + sha.toString(32));
        } catch(Exception e) { e.printStackTrace(); }}public static void main(String[] args) {
        sha("ddddddddddddd"); }}Copy the code

4.AES

AES encryption is symmetric encryption. 128, 192, 256 indicate the key length respectively

AES encryption splits the plaintext into different blocks for encryption

AES, currently widely used in financial accounting, online transactions, wireless communications, digital storage and other fields, has undergone the most rigorous test, but it may one day go the way of DES.

package com.xin;
​
import org.springframework.util.Base64Utils;
​
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
​
public class Aain {
​
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// The default encryption algorithm
​
    /** * AES encryption operation **@paramContent Content to be encrypted *@paramKey Encryption key *@returnReturn Base64 transcoded encrypted data */
    public static String encrypt(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// Create a password
​
            byte[] byteContent = content.getBytes();
​
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// Initialize the cipher to encrypted mode
​
            byte[] result = cipher.doFinal(byteContent);/ / encryption
​
            return Base64Utils.encodeToString(result);// Return via Base64 transcoding
​
        } catch (Exception ex) {
        }
​
        return null;
    }
​
    /** * AES decryption operation **@param content
     * @param key
     * @return* /
    public static String decrypt(String content, String key) {
​
        try {
            / / instantiate
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
​
            // Initialize with the key and set to decryption mode
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
​
            // Perform the operation
            byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
​
            return new String(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
​
        return null;
    }
​
    /** * generates the encryption key **@return* /
    private static SecretKeySpec getSecretKey(final String key) {
        // returns the KeyGenerator object that generates the KeyGenerator for the specified algorithm
        KeyGenerator kg = null;
​
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
​
            //AES requires the key length to be 128
            kg.init(128.new SecureRandom(key.getBytes()));
​
            // Generate a key
            SecretKey secretKey = kg.generateKey();
​
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// Convert to AES private key
        } catch (NoSuchAlgorithmException ex) {
        }
​
        return null;
    }
​
    public static void main(String[] args) {
        String content = "Hello everyone, I am coriander, public account: coriander chat game";
        String key = "sde@5f98H*^hsff%dfs$r344&df8543*er";
        System.out.println("content:" + content);
        String s1 = Aain.encrypt(content, key);
        System.out.println("Encrypted content :" + s1);
        System.out.println("Decrypted content :"+ Aain.decrypt(s1, key)); }}Copy the code

3, summarize

Encryption algorithm is the game protocol must be used, but it is not complex, one-time work, there are large online solutions, but it is necessary to write about it, things will only encounter difficulties at that moment.

And how you can make yourself quit without trying. Ha-ha, forget it. Come on