Hutool crypto encryption and decryption

Posted by paul088 on Fri, 04 Feb 2022 02:08:39 +0100

1. Introduction

In the process of Java development, encryption and decryption are required in many scenarios.

For example, the encryption of sensitive data, the encryption of configuration file information, the encryption of communication data and so on.

Today we will introduce the crypto module in Hutool toolkit

2. Encryption classification

Encryption is divided into three categories:

  • symmetric encryption

    AES and DES are commonly used

  • asymmetric encryption

    RSA and DSA are commonly used

  • digest encryption

    MD5 and SHA-1 are commonly used

3. Overall introduction of crypto module

  • Secret key tool
  • Encrypt Decrypt
  • BCUtil
  • National secret algorithm SmUtil

4. Digest encryption

4.1 indirect

Abstract algorithm is an algorithm that can produce a special output format. The characteristic of this algorithm is that no matter the user inputs the original data with a set length, the ciphertext output after calculation is of fixed length. The principle of this algorithm is to extract a certain form according to certain operation rules. This extraction is a summary, which is closely related to metadata than the data of the summary. As long as the source data changes slightly, the output "summary" will be completely different. Therefore, the amount algorithm based on this principle can provide a sound guarantee for data integrity

However, because the output ciphertext is the fixed length value after extracting metadata, it can not be restored to the original data, that is, the message summarization algorithm is irreversible. Theoretically, the metadata content cannot be obtained through reverse operation. Therefore, its value can usually be used for data integrity verification

4.2 use

This mainly introduces md5 encryption

Basic use

/**
 *  md5 Basic use of
 *      Generate 32-bit ciphertext
 */
@Test
public void MD5BasicTest() {
    System.out.println(new String(DigestUtil.md5("testaaa")));
    // Returns the hexadecimal form de2ec3065687316991579e6b9e6ce143
    System.out.println(DigestUtil.md5Hex("testaa"));
}

Salt addition, salt addition location and summary times

/**
 *  md5 Advanced use of
 *      Location and times of salt addition
 */
@Test
public void MD5Test() {
    // Location and times of salt addition
    String salt = "md5Salt";
    int index = 0;
    int count = 2;
    MD5 md5 = new MD5(salt.getBytes(StandardCharsets.UTF_8), index, count);
    // Returns the hexadecimal format
    System.out.println(md5.digestHex("testaa"));;
}

5. Symmetric encryption

5.1 introduction

Symmetric encryption (also known as private key encryption) refers to the encryption algorithm that uses the same secret key for encryption and decryption. Sometimes it is also called traditional cipher algorithm, that is, the encryption meter can be calculated from the decryption secret key, and the secret key can also be calculated from the encryption secret key. In most symmetric algorithms, the encryption secret key and decryption secret key are the same, so this algorithm is also called private secret key algorithm or single secret key algorithm.

She asked the sender and receiver to agree on a secret key before secure communication.

The security of symmetric algorithm depends on the secret key. Disclosing the secret key means that anyone can decrypt the messages they send and receive, so the confidentiality of the secret key is very important to the security of communication.

5.2 use

AES is introduced here

Basic use

/**
 * Simple to use, directly use the secret key to encrypt and decrypt
 */
@Test
public void AESBasicTest() {
    // Generate a secret key, or specify it manually
    byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();

    // structure
    SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
    // encryption
    System.out.println(new String(symmetricCrypto.encrypt("testaa")));
    // Generate in hexadecimal format
    System.out.println(symmetricCrypto.encryptHex("testaa"));

    // decrypt
    System.out.println(new String(symmetricCrypto.decrypt(symmetricCrypto.encrypt("testaa"))));
    // Decrypt string directly
    System.out.println(symmetricCrypto.decryptStr(symmetricCrypto.encryptHex("testaa")));
}

Advanced use

/**
 * AES Advanced use
 *      mode – Mode mode
 *      padding – Padding Complement mode
 *      key – Key. Three key lengths are supported: 128, 192 and 256 bits
 *      iv – Offset vector, salt must be 16 bits
 *
 *  Disadvantages: affected by iv, the encrypted string is either empty or more than 16 bits
 */
@Test
public void AESTest() {
    // Generate a secret key, or specify it manually
    byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
    String iv = "testiv0000000000";

    AES aes = new AES(Mode.CTS, Padding.PKCS5Padding, key, iv.getBytes(StandardCharsets.UTF_8));

    // encryption
    System.out.println(aes.encryptHex("testaa1234567899"));
    // decrypt
    System.out.println(aes.decryptStr(aes.encrypt("testaa1234567899")));
}

6. Asymmetric encryption

6.1 introduction

For asymmetric encryption, the most commonly used are RSA and DSA

Non heap encryption has two concepts: public key and private key. The private key is owned by itself and the public key is public. According to different applications, we can choose to use different secret keys for encryption

  1. Signature: use private key encryption and public key decryption. It is used for the owner of all public keys to verify the identity of the owner of the private key and to prevent the content published by the owner of the private key from being tampered with, but it is not used to ensure that the content is not obtained by others
  2. Encryption: encrypt with public key and decrypt with private key. It is used to release the galaxy to the public key owner. This information may be tampered with by them, but cannot be obtained by others

6.2 use

Here is RSA

Basic use

/**
 * Basic use
 */
@Test
public void RSABasicTest() {
    RSA rsa = new RSA();
    // Get public and private keys
    System.out.println(rsa.getPublicKey());
    System.out.println(rsa.getPrivateKeyBase64());
    System.out.println(rsa.getPrivateKey());
    System.out.println(rsa.getPrivateKeyBase64());
    // Private key encryption
    System.out.println(new String(rsa.encrypt("testaa", KeyType.PrivateKey)));
    System.out.println(new String(rsa.decrypt(rsa.encrypt("testaa", KeyType.PrivateKey), KeyType.PublicKey)));
    // Public key encryption, private key decryption
    System.out.println(new String(rsa.encrypt("testaa", KeyType.PublicKey)));
    System.out.println(new String(rsa.decrypt(rsa.encrypt("testaa", KeyType.PublicKey), KeyType.PrivateKey)));
}

Advanced use

/**
 * Advanced use
 *  Custom generated public and private keys
 */
@Test
public void RSATest() {
    KeyPair keyPair = SecureUtil.generateKeyPair(AsymmetricAlgorithm.RSA.getValue());
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    System.out.println(publicKey);
    System.out.println(privateKey);
    System.out.println("----------");

    RSA rsa = new RSA(privateKey, publicKey);
    // Private key encryption
    System.out.println(new String(rsa.encrypt("testaa", KeyType.PrivateKey)));
    System.out.println(new String(rsa.decrypt(rsa.encrypt("testaa", KeyType.PrivateKey), KeyType.PublicKey)));
    // Public key encryption, private key decryption
    System.out.println(new String(rsa.encrypt("testaa", KeyType.PublicKey)));
    System.out.println(new String(rsa.decrypt(rsa.encrypt("testaa", KeyType.PublicKey), KeyType.PrivateKey)));

}

7. State secret algorithm (SM)

Hutool has made simplified packaging for Bouncy Castle to realize SM2, SM3 and SM4 in the state secret algorithm.

The state secret algorithm tool package includes:

  • Asymmetric encryption and signature: SM2
  • Abstract signature algorithm: SM3
  • Symmetric encryption: SM4

The state secret algorithm needs to introduce the dependency of Bouncy Castle library.

I won't introduce it

Topics: Java