Summary of common encryption tool classes Base64, DES, AES, RSA, MD5

Keywords: Java encoding JDK git

Article directory

Introduction

In the project, Base64, DES, AES, RSA, MD5 encryption and decryption methods are often used. Every time, they need to search online for half a day. Today, they are simply summed up in one time for memory search.
JDK version: 1.8.0 μ 45
Code location: com.leo.demo.encodetest
Source address: https://gitee.com/leo825/sortalgorithm-demos.git

1. Base64 encryption

Base64 coding is a coding method often used in our program development. It is based on the representation of binary data with 64 printable characters. It is usually used to store and transmit some binary data encoding methods. For details, please refer to Baidu Encyclopedia: base64

package com.leo.demo.encodetest;

import java.util.Base64;

/**
 * @ClassName: Base64Util
 * @Description: Base64 Coding is a coding method which is often used in our program development. It is based on 64 printable characters to represent binary data
 * @Author: leo825
 * @Date: 2020-02-12 17:32
 * @Version: 1.0
 */
public class Base64Util {

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

    /**
     * Use base64 encryption
     *
     * @param content
     * @return
     */
    public static String encryptData(String content) throws Exception {
        return Base64.getEncoder().encodeToString(content.getBytes(CHARSET_UTF_8));
    }

    /**
     * Decryption using base64
     *
     * @param encryptData
     * @return
     */
    public static String decodeDate(String encryptData) throws Exception {
        return new String(Base64.getDecoder().decode(encryptData.getBytes()), CHARSET_UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String str = "hello world, base64";
        System.out.println("Original string:" + str);
        String encodeStr = encryptData(str);
        System.out.println("base64 After encryption:" + encodeStr);
        System.out.println("base64 After decryption:" + decodeDate(encodeStr));
    }
}

2. DES encryption

DES is a group encryption algorithm, which encrypts data in 64 bits. A 64 bit set of plaintext is input from one end of the algorithm, and a 64 bit ciphertext is output from the other end. DES is a symmetric encryption algorithm. Symmetric encryption is the same as encryption and decryption keys.

package com.leo.demo.encodetest;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @ClassName: DESUtil
 * @Description: DES encryption
 * DES It is a common type of symmetric encryption. Its full name is Data Encryption Standard, which is a block algorithm using key encryption.
 * The key length is 64 bit, and the key exceeding the number of bits is ignored. Symmetric encryption, encryption and decryption keys are the same.
 * Symmetric encryption generally divides the string to be encrypted into blocks according to the fixed length. Less than a whole block or just the last special fill character
 * @Author: leo825
 * @Date: 2020-02-12 10:02
 * @Version: 1.0
 */
public class DESUtil {

    private static Key key;
    private static final String PRIVATE_KEY = "f573a9b0";

    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(PRIVATE_KEY.getBytes());
            generator.init(secureRandom);
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Encryption, return the encryption string of BASE64
     * @param str
     * @return
     */
    public static String getEncryptString(String str) throws Exception {
        byte[] strBytes = str.getBytes("UTF-8");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptStrBytes = cipher.doFinal(strBytes);
        return Base64.getEncoder().encodeToString(encryptStrBytes);
    }

    /**
     * Decrypt BASE64 encrypted string
     * @param str
     * @return
     */
    public static String getDecryptString(String str) throws Exception {
        byte[] strBytes = Base64.getDecoder().decode(str);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] encryptStrBytes = cipher.doFinal(strBytes);
        return new String(encryptStrBytes, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        String name = "root";
        String password = "1qaz!QAZ";
        String encryname = getEncryptString(name);
        String encrypassword = getEncryptString(password);
        System.out.println("Encryption:" + encryname);
        System.out.println("Encryption:" + encrypassword);

        System.out.println("Decrypt:" + getDecryptString(encryname));
        System.out.println("Decrypt:" + getDecryptString(encrypassword));
    }
}

3. AES encryption

AES advanced encryption standard is the most common symmetric encryption algorithm (used for encrypted transmission of wechat applets). AES is also a symmetric encryption algorithm. Symmetric encryption is the same as encryption and decryption keys.

package com.leo.demo.encodetest;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
/**
 * @ClassName: AESUtil
 * @Description: AES In order to replace DES, AES has better security, efficiency and flexibility
 * @Author: leo825
 * @Date: 2020-02-12 09:46
 * @Version: 1.0
 */
public class AESUtil {

    /*
     * Encryption (external exposure)
     */
    public static String encryptData(String privateKey, String content) throws Exception {
        KeyGenerator keygen = getKeyGenerator(privateKey);
        SecretKey key = new SecretKeySpec(keygen.generateKey().getEncoded(), "AES");
        return Base64.getEncoder().encodeToString(encrypt(key, content.getBytes("UTF-8")));
    }

    /*
     * Decryption (external exposure)
     */
    public static String decryptData(String privateKey, String content) throws Exception {
        KeyGenerator keygen = getKeyGenerator(privateKey);
        SecretKey key = new SecretKeySpec(keygen.generateKey().getEncoded(), "AES");
        return new String(decrypt(key, Base64.getDecoder().decode(content)), "UTF-8");
    }

    private static KeyGenerator getKeyGenerator(String privateKey) throws NoSuchAlgorithmException {
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(privateKey.getBytes());
        keygen.init(128, secureRandom);
        return keygen;
    }

    private static byte[] encrypt(Key key, byte[] srcBytes) {
        if (key != null) {
            try {
                // Cipher is responsible for encryption or decryption based on AES
                Cipher cipher = Cipher.getInstance("AES");
                // Initialize Cipher object
                cipher.init(Cipher.ENCRYPT_MODE, key);
                // Encrypt, save and return
                return cipher.doFinal(srcBytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static byte[] decrypt(Key key, byte[] encBytes) {
        if (key != null) {
            try {
                Cipher cipher = Cipher.getInstance("AES");
                //Initialize Cipher object
                cipher.init(Cipher.DECRYPT_MODE, key);
                //Decrypt
                return cipher.doFinal(encBytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        String privateKey = "ABC";
        String content = "ASD456";
        String m = encryptData(privateKey, content);
        System.out.println("The content to be encrypted is:" + content);
        System.out.println("Based on the private key:" + privateKey + ",The encrypted ciphertext is:" + m);
        System.out.println("Based on the private key:" + privateKey + ",The decrypted plaintext is:" + decryptData(privateKey, m));
    }

}

4. RSA encryption

RSA encryption is a kind of asymmetric encryption. The decryption can be completed without passing the key directly. This can ensure the security of information and avoid the risk of being cracked by directly transferring the key. It is a process of encryption and decryption by a pair of keys, which are called public key and private key respectively. There is a mathematical correlation between them. The principle of this encryption algorithm is the difficulty of factoring a maximum integer to ensure the security. The private key is usually kept by individuals, and the public key is public (possibly held by multiple people at the same time).

package com.leo.demo.encodetest;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
 * @ClassName: RSAUtil
 * @Description:
 *  RSA Encryption algorithm is the most influential public key encryption algorithm, and is generally considered to be one of the best public key schemes.
 *  RSA It is the first algorithm that can be used for encryption and digital signature at the same time. It can resist all known password attacks so far, and has been recommended as the public key data encryption standard by ISO.
 * @Author: leo825
 * @Date: 2020-02-12 09:35
 * @Version: 1.0
 */

public class RSAUtil {

    /**
     * Encryption (external exposure)
     * If the public key is used to encrypt the data, only the corresponding private key can be used for decryption.
     * If the private key is used to encrypt the data, only the corresponding public key can be used for decryption.
     *
     * @param keyStr
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptData(String keyStr, String data, Boolean isPublicKey) throws Exception {
        if (StringUtils.isEmpty(keyStr)) {
            return "";
        }
        return encryptBASE64(encrypt(getKey(keyStr, isPublicKey), data.getBytes()));
    }

    /**
     * Decryption (external exposure)
     * If the public key is used to encrypt the data, only the corresponding private key can be used for decryption.
     * If the private key is used to encrypt the data, only the corresponding public key can be used for decryption.
     *
     * @param keyStr
     * @param data
     * @return
     * @throws Exception
     */
    public static String decryptData(String keyStr, String data, Boolean isPublicKey) throws Exception {
        if (StringUtils.isEmpty(keyStr)) {
            return "";
        }
        return new String(decrypt(getKey(keyStr, isPublicKey), decryptBASE64(data)), "UTF-8");
    }

    /**
     * encryption
     *
     * @param key
     * @param srcBytes
     * @return
     */
    private static byte[] encrypt(Key key, byte[] srcBytes) {
        if (key != null) {
            try {
                //Cipher is responsible for encryption or decryption, based on RSA
                Cipher cipher = Cipher.getInstance("RSA");
                //Initialize Cipher object
                cipher.init(Cipher.ENCRYPT_MODE, key);
                //Encrypt and return
                return cipher.doFinal(srcBytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Decrypt
     *
     * @param key
     * @param encBytes
     * @return
     */
    private static byte[] decrypt(Key key, byte[] encBytes) {
        if (key != null) {
            try {
                Cipher cipher = Cipher.getInstance("RSA");
                //Initialize Cipher object
                cipher.init(Cipher.DECRYPT_MODE, key);
                //Decrypt and return results
                return cipher.doFinal(encBytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Get public or private key object according to key
     *
     * @param keyStr
     * @param isPublicKey
     * @return
     * @throws Exception
     */
    private static Key getKey(String keyStr, Boolean isPublicKey) throws Exception {
        if (isPublicKey) {
            return getPublicKey(keyStr);
        } else {
            return getPrivateKey(keyStr);
        }
    }

    /**
     * Get the public key object according to the public key
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static RSAPublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

    /**
     * Get private object according to private key
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static RSAPrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }

    /**
     * Get public / private Key
     *
     * @return
     */
    private static KeyPair getRSAKey() {
        KeyPair keyPair = null;
        try {
            //Generate public key and private key pairs, and generate objects based on RSA algorithm
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            //Initializes the key pair generator with a key size of 1024 bits
            keyPairGen.initialize(1024);
            //Generate a key pair and save it in keyPair
            keyPair = keyPairGen.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return keyPair;
    }

    /**
     * BASE64Decoder on string
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }

    /**
     * BASE64Encoder byte array
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static String encryptBASE64(byte[] key) {
        return Base64.getEncoder().encodeToString(key);
    }

    public static void main(String[] args) {
        // A pair of generated key s are saved
        try {
            //Get private key and public key
            KeyPair keyPair = getRSAKey();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

            String pubKey = encryptBASE64(publicKey.getEncoded());
            String priKey = encryptBASE64(privateKey.getEncoded());
            System.out.println("Public key:" + pubKey);
            System.out.println("Private key:" + priKey);

            // test
            String message = "QWERDF";

            System.out.println("Plaintext:" + message);
            String jiami = encryptData(pubKey, message, true);
            System.out.println("After public key encryption:" + jiami);
            String jiemi = decryptData(priKey, jiami, false);
            System.out.println("The result of decryption with private key is:" + jiemi);

            jiami = encryptData(priKey, message, false);
            System.out.println("After private key encryption:" + jiami);
            jiemi = decryptData(pubKey, jiami, true);
            System.out.println("The result of decryption with public key is:" + jiemi);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

5. MD5 encryption

It is mainly for the encryption of password. MD5 encryption is irreversible. After encryption, it cannot be decrypted. The encrypted data is directly used as the password. Thus, even if the MD5 value of the user's password is obtained, the user's password cannot be obtained. Even the administrator cannot know the user's password.

package com.leo.demo.encodetest;

import java.security.MessageDigest;

/**
 * @ClassName: MD5Util
 * @Description: MD5 encryption
 * MD5,Message digest algorithm (MD5 message digest algorithm).
 * It is a widely used cryptographic hash function that changes the operation of data (such as a piece of text) into another fixed length value,
 * It is the basic principle of hash algorithm. It can generate a 128 bit (16 byte) hash value to ensure the integrity and consistency of information transmission
 * @Author: leo825
 * @Date: 2020-02-12 18:02
 * @Version: 1.0
 */
public class MD5Util {

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

    private static final String hexDigIts[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * MD5 encryption
     *
     * @param origin      character
     * @param charsetname Code
     * @return
     */
    public static String encodeData(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (null == charsetname || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception e) {
        }
        return resultString;
    }

    /**
     * The default utf-8 is used for encoding, 32-bit lowercase
     * @param origin
     * @return
     */
    public static String encodeData32(String origin) {
        return encodeData(origin, CHARSET_UTF_8);
    }

    /**
     * utf-8 used by default for encoding, 32-bit uppercase
     * @param origin
     * @return
     */
    public static String encodeData32UpperCase(String origin){
        return encodeData(origin, CHARSET_UTF_8).toUpperCase();
    }

    /**
     * The default utf-8 is used for encoding, 16 bit lowercase
     * @param origin
     * @return
     */
    public static String encodeData16(String origin){
        return encodeData(origin, CHARSET_UTF_8).substring(8,24);
    }

    /**
     * The default utf-8 is used for encoding, 16 bit uppercase
     * @param origin
     * @return
     */
    public static String encodeData16UpperCase(String origin){
        return encodeData(origin, CHARSET_UTF_8).substring(8, 24).toUpperCase();
    }


    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }


    public static void main(String[] args) {
        String username = "Zhang San";
        System.out.println(encodeData16(username));
        System.out.println(encodeData16UpperCase(username));
        System.out.println(encodeData32(username));
        System.out.println(encodeData32UpperCase(username));
    }


}
Published 21 original articles, won praise 3, 10000 visitors+
Private letter follow

Posted by hitman6003 on Wed, 12 Feb 2020 03:09:45 -0800