The world of cryptography

If you are a gang boss, usually communicate with subordinates, how to ensure their information security?

In the first series of Sherlock, there was a story about how to crack encrypted Mafia communications.

This type of password makes use of a password dictionary.

Could the password itself be a book, like the familiar Bible, to Kill a Mockingbird, or a map of New York?

The advantage of this type of encryption is that if you don’t know the dictionary itself, it’s almost impossible to crack. It’s easy to use, and you can even change your dictionary with your staff regularly.

When it comes to cryptography, another story that has to be told is that of code-breaking during World War II.

During world War II, The ENIGMA encryption machine invented by Germany made communication encryption leap from the era of manual handwriting to the era of machine operation, which also made human decoding a little powerless.

In order to decipher the German encryption machine, from Cambridge to find three excellent mathematicians: Geoffrey Period, Wellesman, Alan. Turing.

Speaking of Alan Turing, I’m sure you all know him. If you don’t, please bookmark this article and read on.

As the saying goes, only magic can defeat magic. That would make Kibo… Oh, I’m sorry, I’ll leave it to Alan.

Alan thought it was possible to use the mathematical crib method to break ENIGMA, and deciphered most of the German intelligence information in the later period.

In the future, we will use machines to defeat machines.

Reversibility of encryption

Encryption algorithms can be divided into: reversible encryption and irreversible encryption; Reversible encryption can be divided into symmetric encryption and asymmetric encryption.

Of course, in general communications, we need to decrypt.

This paper mainly introduces four most famous encryption algorithms in modern times: DES 3DES AES and SM4.

The DES algorithm

Introduction to the

DES is called Data Encryption Standard. It is a block algorithm that encrypts Data with a key. It was identified as FIPS by the National Bureau of Standards of the FEDERAL Government of the United States in 1977 and authorized to be used in unclassified government communications. The algorithm was then widely spread internationally.

Design principles

DES design uses two principles of block cipher design: confusion and diffusion, its purpose is to counter the enemy’s statistical analysis of the cipher system.

Obfuscation is to complicate the relationship between the statistical properties of the ciphertext and the value of the key as much as possible so that the dependencies between the key and the plaintext and the ciphertext are not exploitable to the cryptanalyst.

The effect of diffusion is to spread the influence of each plaintext bit to as many output ciphertext bits as quickly as possible, so as to eliminate the statistical structure of the plaintext in a large number of ciphertext bits, and to spread the influence of each key bit to as many ciphertext bits as quickly as possible, so as to prevent the decryption of the key segment by segment.

Ps: Basic modern encryption algorithms should follow these two principles, otherwise they will be statistical attacks.

Introduction to use

The simplest example of a DES implementation is provided here.

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

/** * DES tool class **@author binbin.hou
 * @since0.0.6 * /
public final class DesUtil {

    private DesUtil(a) {}/**
     * des
     *
     * @since0.0.6 * /
    private static final String DES = "DES";

    /** * encrypt **@paramPlainText Content to be encrypted@param"Password," password *@returnEncryption result@since0.0.6 * /
    public static byte[] encrypt(String plainText, String password) {
        byte[] bytes = plainText.getBytes();
        return encrypt(bytes, password);
    }

    /** * encrypt **@paramPlainText Content to be encrypted@param"Password," password *@returnEncryption result@since0.0.6 * /
    public static byte[] encrypt(byte[] plainText, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            // Create a key factory and use it to convert DESKeySpec to
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            SecretKey secretKey = keyFactory.generateSecret(desKey);
            // the Cipher object is actually encrypted
            Cipher cipher = Cipher.getInstance(DES);
            // Initialize a Cipher object with a key
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
            // Now, get the data and encrypt it
            // The encryption operation is officially performed
            return cipher.doFinal(plainText);
        } catch (Exception e) {
            throw newSecretRuntimeException(e); }}/** * decrypt **@param src      byte[]
     * @param password String
     * @returnDecrypt result@since0.0.6 * /
    public static byte[] decrypt(byte[] src, String password) {
        try {
            // The DES algorithm requires a trusted random source
            SecureRandom random = new SecureRandom();
            // Create a DESKeySpec object
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            // Create a key factory
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            // Convert DESKeySpec to SecretKey
            SecretKey secretKey = keyFactory.generateSecret(desKey);
            // The Cipher object completes decryption
            Cipher cipher = Cipher.getInstance(DES);
            // Initialize a Cipher object with a key
            cipher.init(Cipher.DECRYPT_MODE, secretKey, random);
            // Start the decryption operation
            return cipher.doFinal(src);
        } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
            throw newSecretRuntimeException(e); }}/** * decrypt **@param src      byte[]
     * @param password String
     * @returnDecrypt result@since0.0.6 * /
    public static String decryptToString(byte[] src, String password,
                                         String charset) {
        try {
            byte[] bytes = decrypt(src, password);

            return new String(bytes, charset);
        } catch (UnsupportedEncodingException e) {
            throw newSecretRuntimeException(e); }}/** * decrypt **@param src      byte[]
     * @param password String
     * @returnDecrypt result@since0.0.6 * /
    public static String decryptToString(byte[] src, String password) {
        return decryptToString(src, password, "UTF-8"); }}Copy the code

The test code

The test code is as follows:

public static void main(String[] args) {
    // The content to be encrypted
    String str = "Test content";
    // The password must be a multiple of 8
    String password = "01234567";
    byte[] result = DesUtil.encrypt(str, password);
    System.out.println("After encryption:" + HexUtil.byteToHexString(result));
    // Decrypt the above content directly
    String decryResult = DesUtil.decryptToString(result, password);
    System.out.println("After decryption:" + decryResult);
}
Copy the code

The log is as follows:

After the encryption: 77 c25c0143f544cfff102e43bde1abe1 decrypted: test contentCopy the code

Develop reading

Specific algorithm principle recommended reading:

Introduction to the DES encryption algorithm and the algorithm principle: houbb. Making. IO / 2020/06/17 /…

3DES

Algorithm is introduced

3DES (or Triple DES) is a common name for a block password of the Triple Data Encryption Algorithm (TDEA).

It is equivalent to applying the DES encryption algorithm three times to each block of data.

Due to the enhancement of computer computing power, the key length of the original DES password becomes easy to be cracked by violence;

3DES is designed to provide a relatively simple way to avoid such attacks by increasing the key length of DES, rather than designing a new block cipher algorithm.

Introduction to Java

The 3DES tool class is implemented as follows:

import com.github.houbb.heaven.constant.CharsetConst;
import com.github.houbb.secret.api.exception.SecretRuntimeException;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/** * 3DES tool class **@author binbin.hou
 * @since0.0.7 * /
public final class TripleDesUtil {

    private TripleDesUtil(a) {}/** * Algorithm name **@since0.0.7 * /
    private static final String ALGORITHM = "DESede";

    /** * encryption function **@paramKeyBytes Encryption key. The length is 24 bytes *@paramPlainBytes The encrypted data buffer (source) *@returnResults *@since0.0.7 * /
    public static byte[] encrypt(byte[] keyBytes, byte[] plainBytes) {
        try {
            // Generate the key
            SecretKey deskey = new SecretKeySpec(keyBytes, ALGORITHM);
            / / encryption
            Cipher c1 = Cipher.getInstance(ALGORITHM);
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            return c1.doFinal(plainBytes);
        } catch (Exception e1) {
            throw newSecurityException(e1); }}/** * encryption function **@paramKeyBytes Encryption key. The length is 24 bytes *@paramPlainText An encrypted data buffer (source) *@returnResults *@since0.0.7 * /
    public static byte[] encrypt(byte[] keyBytes, String plainText) {
        return encrypt(keyBytes, plainText.getBytes());
    }

    /** * decrypt function *@paramKeyBytes Encryption key. The length is 24 bytes *@paramSecretBytes Encrypted buffer *@returnResults *@since0.0.7 * /
    public static byte[] decrypt(byte[] keyBytes, byte[] secretBytes) {
        try {
            // Generate the key
            SecretKey deskey = new SecretKeySpec(keyBytes, ALGORITHM);
            / / decryption
            Cipher c1 = Cipher.getInstance(ALGORITHM);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            return c1.doFinal(secretBytes);
        } catch (Exception e1) {
            throw newSecretRuntimeException(e1); }}/** * decrypt function *@paramKeyBytes Encryption key. The length is 24 bytes *@paramSecretBytes Encrypted buffer *@paramCharsetName Encoding name * *@returnResults *@since0.0.7 * /
    public static String decryptToString(byte[] keyBytes, byte[] secretBytes, String charsetName) {
        try {
            byte[] bytes = decrypt(keyBytes, secretBytes);

            return new String(bytes, charsetName);
        } catch (UnsupportedEncodingException e) {
            throw newSecretRuntimeException(e); }}/** * decrypt function *@paramKeyBytes Encryption key. The length is 24 bytes *@paramSecretBytes Encrypted buffer * *@returnResults *@since0.0.7 * /
    public static String decryptToString(byte[] keyBytes, byte[] secretBytes) {
        returndecryptToString(keyBytes, secretBytes, CharsetConst.UTF8); }}Copy the code

test

public static void main(String[] args) {
    String text = "I love China!";
    String password = "123456781234567812345678";
    byte[] bytes = encrypt(password.getBytes(), text);
    System.out.println(HexUtil.byteToHexString(bytes));
    String plainText = decryptToString(password.getBytes(), bytes);
    System.out.println(plainText);
}
Copy the code

Log message:

A60CBC97EEFF2958DF4384215E0838C0 I love Chinese!Copy the code

Develop reading

Specific algorithm principle recommended reading:

Introduction to 3 des encryption algorithm and the algorithm principle: houbb. Making. IO / 2020/06/17 /…

AES algorithm

Introduction of algorithm

Advanced Encryption Standard (AES) in cryptography, also known as Rijndael Encryption, is a block Encryption Standard adopted by the U.S. federal government.

In 2006, advanced Encryption Standard has become one of the most popular algorithms in symmetric key encryption.

This algorithm is more secure than 3DES.

Introduction to Java

Java utility classes are implemented as follows.

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

/** * 3DES tool class **@author binbin.hou
 * @since0.0.7 * /
public final class AesUtil {

    private AesUtil(a) {}/** * Algorithm name **@since0.0.7 * /
    private static final String ALGORITHM = "AES";

    /** * Encrypts the specified plainText according to the key@paramPlainBytes expressly *@paramKeyBytes password *@returnEncrypted ciphertext. *@since0.0.8 * /
    public static byte[] encrypt(byte[] plainBytes, byte[] keyBytes) {
        try {
            SecretKey secretKey = getSecretKey(keyBytes);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return cipher.doFinal(plainBytes);
        } catch (Exception e) {
            throw newRuntimeException(e); }}/** * Decrypts the specified cipherBytes according to the key@paramCipherBytes Encrypted ciphertext *@paramKeyBytes secret key *@returnDecrypted plaintext. *@since0.0.8 * /
    public static byte[] decrypt(byte[] cipherBytes, byte[] keyBytes) {
        try {
            SecretKey secretKey = getSecretKey(keyBytes);

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(cipherBytes);
        } catch (Exception e) {
            throw newRuntimeException(e); }}/** * get the encryption key **@param keySeed seed
     * @returnResults *@since0.0.8 * /
    private static SecretKey getSecretKey(byte[] keySeed) {
        try {
            // Avoid random problems with Linux
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keySeed);
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(secureRandom);
            return generator.generateKey();
        } catch (Exception e) {
            throw newRuntimeException(e); }}}Copy the code

The test code

public static void main(String[] args) throws UnsupportedEncodingException {
    String text = "I love China!";
    // Key, 256 bits 32 bytes
    String password = "uBdUx82vPHkDKb284d7NkjFoNcKWBuka";
    byte[] bytes = encrypt(text.getBytes(), password.getBytes());
    String text2 = new String(decrypt(bytes, password.getBytes()), "UTF-8");
    System.out.println(text2);
}
Copy the code

Output: I love China!

Develop reading

Specific algorithm principle recommended reading:

Introduction to the AES encryption algorithm and the algorithm principle: houbb. Making. IO / 2020/06/17 /…

SM4 algorithm

Introduction of algorithm

SM4 is a block cipher algorithm with a block length of 128 bits (16 bytes, 4 words) and a key length of 128 bits (16 bytes, 4 words).

The encryption and decryption process uses 32 rounds of iteration mechanism (similar to DES and AES), and each round requires a round key (similar to DES and AES).

SM4 algorithm, also known as the state secret algorithm. Because this is the Chinese own encryption algorithm, the domestic financial and other fields will use.

Introduction to Java

Maven rely on

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.59</version>
</dependency>
Copy the code

Tool encapsulation

import com.github.houbb.secret.api.exception.SecretRuntimeException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;

/** * Sm4 country secret algorithm **@author binbin.hou
 * @since0.0.5 * /
public final class Sm4Util {

    private Sm4Util(a) {}static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ENCODING = "UTF-8";

    private static final String ALGORITHM_NAME = "SM4";

    /** * PKCS5Padding NoPadding rule, PKCS5Padding missing 0, NoPadding not */
    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    /** * ECB encryption mode, no vector *@paramAlgorithmName algorithmName *@paramMode pattern *@param key           key
     * @returnResults the * /
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /** * SM4 encryption * Encryption mode: ECB ciphertext length is not fixed, will change with the length of the encrypted string **@paramHexKey Hexadecimal key (case ignored) *@paramPlainText String * to be encrypted@returnReturns the hexadecimal encrypted string *@since0.0.5 * /
    public static String encryptEcb(String hexKey, String plainText) {
        try {
            String cipherText = "";
            // Hexadecimal string -->byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // String-->byte[]
            // Use this line when the encrypted data is a hexadecimal string
            byte[] srcData = plainText.getBytes(ENCODING);
            // An encrypted array
            byte[] cipherArray = encryptEcbPadding(keyData, srcData);
            // byte[]-->hexString
            cipherText = ByteUtils.toHexString(cipherArray);
            return cipherText;
        } catch (Exception exception) {
            throw newSecretRuntimeException(exception); }}/** * Encryption mode Ecb **@paramThe key secret key *@paramData Indicates the data to be encrypted@returnByte array *@since0.0.5 * /
    public static byte[] encryptEcbPadding(byte[] key, byte[] data) {
        try {
            // Claims Ecb code, using the second argument to determine whether to encrypt or decrypt
            Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception exception) {
            throw newSecretRuntimeException(exception); }}/ / decryption * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

    /** * SM4 decryption ** Decryption mode: use ECB *@paramHexKey Hexadecimal key *@paramCipherText An encrypted hexadecimal string (case ignored) *@returnDecrypted string *@since0.0.5 * /
    public static String decryptEcb(String hexKey, String cipherText) {
        try {
            // Used to receive the decrypted string
            String decryptStr = "";
            // hexString-->byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // hexString-->byte[]
            byte[] cipherData = ByteUtils.fromHexString(cipherText);
            / / decryption
            byte[] srcData = decryptEcbPadding(keyData, cipherData);
            // byte[]-->String
            decryptStr = new String(srcData, ENCODING);
            return decryptStr;
        } catch (Exception exception) {
            throw newSecretRuntimeException(exception); }}/** * decrypt **@paramThe key secret key *@paramCipherText cipherText *@returnResults *@since0.0.5 * /
    public static byte[] decryptEcbPadding(byte[] key, byte[] cipherText) {
        try {
            // Generate THE Ecb code, using the second argument to determine whether to encrypt or decrypt
            Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(cipherText);
        } catch (Exception exception) {
            throw newSecretRuntimeException(exception); }}/** * validate data *@param hexKey key
     * @paramCipherText cipherText *@paramPlainText expressly *@returnResults *@since0.0.5 * /
    public static boolean verifyEcb(String hexKey, String cipherText, String plainText) {
        try {
            // Used to receive verification results
            boolean flag = false;
            // hexString-->byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // Convert hexadecimal strings to arrays
            byte[] cipherData = ByteUtils.fromHexString(cipherText);
            / / decryption
            byte[] decryptData = decryptEcbPadding(keyData, cipherData);
            // Convert the original string to byte[]
            byte[] srcData = plainText.getBytes(ENCODING);
            // Check whether the two arrays are consistent
            flag = Arrays.equals(decryptData, srcData);
            return flag;
        } catch (Exception exception) {
            throw newSecretRuntimeException(exception); }}}Copy the code

The test code

System.out.println("Start * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
String plainText = "96C63180C2806ED1F47B859DE501215B";
System.out.println("Before encryption:" + plainText);
// Custom 32-bit hexadecimal key
String key = "86C63180C2806ED1F47B859DE501215B";
String cipher = encryptEcb(key, plainText);/ / sm4 encryption
System.out.println("After encryption:" + cipher);
// Check whether the data is the same before and after encryption
System.out.println("Check:" + verifyEcb(key, cipher, plainText));
plainText = decryptEcb(key, cipher);/ / decryption
System.out.println("After decryption:" + plainText);
System.out.println("The end of the * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
Copy the code

Corresponding log:

Start * * * * * * * * * * * * * * * * * * * * * * * * * * * * before encryption: after the 96 c63180c2806ed1f47b859de501215b encryption: After the 063 c352bcec7d360da455ebaab2595347d0aa493d2a80a72396771b5585a49f81642326904c036af50b50f92e86cb274 check: true decryption: 96 c63180c2806ed1f47b859de501215b end * * * * * * * * * * * * * * * * * * * * * * * * * * * *Copy the code

Develop reading

Specific algorithm principle recommended reading:

Introductory SM4 encryption algorithm and the algorithm principle: houbb. Making. IO / 2020/06/17 /…

The fifth largest encryption algorithm

Of course, there are five of the four major encryption algorithms. Isn’t that common sense?

Andrew: Why, why didn’t I know that?

Finally, let’s talk about Base64, another common algorithm.

Algorithm is introduced

Strictly speaking, Base64 is not used for encryption, more for encoding, decoding.

Base64 is a method of combining 64 characters from any Binary data into a string. The Binary data and string data are easily interchangeable with each other.

In practice, Base64 is used to represent the encrypted content of strings, in addition to visualizing Binary data.

Java tools

import com.github.houbb.heaven.util.lang.StringUtil;
import com.github.houbb.secret.api.exception.SecretRuntimeException;

import java.io.UnsupportedEncodingException;

/** * Base64 utility class ** transcoding class *@author binbin.hou
 * @since0.0.4 * /
public final class Base64Util {

    private Base64Util(a) {}private static final char[] ALPHABET_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();

    private static final byte[] CODES = new byte[256];

    static {
        for (int i = 0; i < 256; i++) {
            CODES[i] = -1;
        }
        for (int i = 'A'; i <= 'Z'; i++) {
            CODES[i] = (byte) (i - 'A');
        }
        for (int i = 'a'; i <= 'z'; i++) {
            CODES[i] = (byte) (26 + i - 'a');
        }
        for (int i = '0'; i <= '9'; i++) {
            CODES[i] = (byte) (52 + i - '0');
        }
        CODES['+'] = 62;
        CODES['/'] = 63;
    }

    /** * Encodes the raw data to base64 encoding **@paramThe data data *@since0.0.4 * /
    public static char[] encode(byte[] data) {
        char[] out = new char[((data.length + 2) / 3) * 4];

        for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
            boolean quad = false;
            boolean trip = false;
            int val = (0xFF & (int) data[i]);
            val <<= 8;
            if ((i + 1) < data.length) {
                val |= (0xFF & (int) data[i + 1]);
                trip = true;
            }
            val <<= 8;
            if ((i + 2) < data.length) {
                val |= (0xFF & (int) data[i + 2]);
                quad = true;
            }
            out[index + 3] = ALPHABET_CHARS[(quad ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 2] = ALPHABET_CHARS[(trip ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 1] = ALPHABET_CHARS[val & 0x3F];
            val >>= 6;
            out[index + 0] = ALPHABET_CHARS[val & 0x3F];
        }
        return out;
    }

    /** * Decodes base64 encoded data into raw data **@paramData array *@since0.0.4 * /
    public static byte[] decode(char[] data) {
        int len = ((data.length + 3) / 4) * 3;
        if (data.length > 0 && data[data.length - 1] = ='=') {
            --len;
        }
        if (data.length > 1 && data[data.length - 2] = ='=') {
            --len;
        }
        byte[] out = new byte[len];
        int shift = 0;
        int accum = 0;
        int index = 0;
        for (char datum : data) {
            int value = CODES[datum & 0xFF];
            if (value >= 0) {
                accum <<= 6;
                shift += 6;
                accum |= value;
                if (shift >= 8) {
                    shift -= 8;
                    out[index++] = (byte) ((accum >> shift) & 0xff); }}}if(index ! = out.length) {throw new SecretRuntimeException("miscalculated data length!");
        }
        return out;
    }

    /** * code *@paramThe text text *@returnResults *@since0.0.4 * /
    public static char[] encode(String text) {
        if(StringUtil.isEmpty(text)) {
            return new char[] {}; }byte[] data = text.getBytes();

        return encode(data);
    }

    /** * is encoded as a string **@paramThe text text *@returnResults *@since0.0.4 * /
    public static String encodeToString(String text) {
        if(StringUtil.isEmpty(text)) {
            return text;
        }
        char[] chars = encode(text);

        return new String(chars);
    }

    /** * Decodes base64 encoded data into raw data **@paramThe text decoding *@since0.0.4 * /
    public static byte[] decode(String text) {
        if(StringUtil.isEmpty(text)) {
            return new byte[] {}; }char[] chars = text.toCharArray();
        return decode(chars);
    }

    /** * Decodes base64 encoded data into raw data **@paramThe text decoding *@paramCharset code *@since0.0.4 * /
    public static String decodeToString(String text, String charset) {
        try {
            byte[] bytes = decode(text);

            return new String(bytes, charset);
        } catch (UnsupportedEncodingException e) {
            throw newSecretRuntimeException(e); }}}Copy the code

test

public static void main(String[] args) {
    String text = "I love China!";
    String base64 = encodeToString(text);
    System.out.println(base64);
    String decode64 = decodeToString(base64, "UTF-8");
    System.out.println(decode64);
}
Copy the code

The output is as follows:

I love China!Copy the code

Develop reading

Specific algorithm principle recommended reading:

Introduction to BASE64 encryption algorithm and the algorithm principle: houbb. Making. IO / 2020/06/17 /…

summary

The information age has been pursuing two metrics: speed and safety (not passion).

Security algorithm is always evolving with the progress of The Times, is a never-ending battle of offense and defense.

For all the algorithms in this paper, I have done a unified summary of the implementation of coding, easy to use. Interested can pay attention to [Lao Ma Xiao Xifeng], background reply [encryption] can be obtained.

In addition, sometime we can talk about irreversible encryption, and asymmetric encryption.

I am old ma, looking forward to meeting with you next time.