Simple AES Encryption and Decryption Demo - Take you to understand AES

1. Introduction to AES

        The full name of AES is Advanced Encryption Standard, which means Advanced Encryption Standard. Its appearance is mainly to replace the DES encryption algorithm, because we all know that the key length of the DES algorithm is 56Bit, so the theoretical security strength of the algorithm is 2 to the 56th power. However, the middle and late twentieth century was the stage of rapid development of computers. The progress of component manufacturing technology made the processing ability of computers stronger and stronger. Although the encryption method of 3DES appeared, its encryption time was three times that of the DES algorithm. Many, the group size of 64Bit is relatively small, so it still cannot meet people's requirements for security. So on January 2, 1997, the National Institute of Standards and Technology announced that it hoped to solicit advanced encryption standards to replace DES. AES has also received responses from many cryptographers around the world, and many people have submitted their own algorithms successively. In the end, 5 candidate algorithms entered the final round: Rijndael, Serpent, Twofish, RC6 and MARS. Finally, after rigorous steps such as security analysis and software and hardware performance evaluation, the Rijndael algorithm won.

        In the Call for Cryptography Standards, all AES candidate submissions must meet the following criteria:

  • A block cipher with a block size of 128 bits.
  • Three cryptographic standards must be supported: 128-bit, 192-bit, and 256-bit.
  • Safer than other algorithms submitted.
  • Efficient in both software and hardware implementation.

        The AES cipher is basically the same as the block cipher Rijndael, and the Rijndael block size and key size can be 128 bits, 192 bits, and 256 bits. However, AES only requires a packet size of 128 bits, so only Rijndael with a packet length of 128Bit is called the AES algorithm. This article only analyzes the Rijndael algorithm with a packet size of 128 bits and a key length of 128 bits. The processing method of the key length of 192 bits and 256 bits is similar to that of 128 bits, except that every time the key length increases by 64 bits, the number of cycles of the algorithm will increase by 2 rounds, 128-bit cycle 10 rounds, 192-bit cycle 12 rounds , 256-bit cycle 14 rounds.

2. AES specific mathematical knowledge

        Slightly... Interested students can check the information by themselves

3. Important components of AES encryption and decryption

1. key

        The key is the foundation of the AES algorithm for encryption and decryption. Symmetric encryption algorithms are symmetrical because they require the same key for encryption and decryption of plaintext. AES supports three key lengths: 128-bit, 192-bit, and 256-bit. The AES128, AES192, and AES256 that everyone usually refers to actually refer to the use of the AES algorithm for keys of different lengths.

2. Filling

        To understand the concept of padding, we must first understand the block encryption characteristics of AES. What is block encryption? Let's take a look at the picture below: When the AES algorithm encrypts plaintext, it does not encrypt the entire plaintext into a whole piece of ciphertext, but splits the plaintext into independent plaintext blocks. The length of each plaintext block is 128bit. These plaintext blocks are processed by the AES encryptor to generate independent ciphertext blocks, and these ciphertext blocks are spliced ​​together to form the final AES encryption result. If the length of a piece of plaintext is 192bit, if it is divided into one plaintext block per 128bit, the second plaintext block is only 64bit, which is less than 128bit. What should we do at this time? It is necessary to pad the plaintext block (Padding).

        Filling involves the following three fill modes:

NoPadding:

        No padding is done, but the plaintext must be an integer multiple of 16 bytes.

PKCS5Padding (default):

        If the plaintext block is less than 16 bytes (128bit), the corresponding number of characters is added at the end of the plaintext block, and the value of each byte is equal to the number of missing characters. For example, plaintext: {1,2,3,4,5,a,b,c,d,e}, if 6 bytes are missing, it will be completed as {1,2,3,4,5,a,b, c,d,e,6,6,6,6,6,6}

ISO10126Padding:

        If the plaintext block is less than 16 bytes (128bit), the corresponding number of bytes is added at the end of the plaintext block, the last character value is equal to the number of missing characters, and other characters are filled with random numbers. For example, plaintext: {1,2,3,4,5,a,b,c,d,e}, if 6 bytes are missing, it may be completed as {1,2,3,4,5,a,b ,c,d,e,5,c,3,G,$,6}

4. Java Code Demo

The interface api code is as follows:

controller layer:

 

service interface: 

impl implementation class: 

Tools:

package com.example.demo.utils;

import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;


@Component
public class AESUtil {
    private static final String IV = "3412566146136412";
    private static final String ENCODING = "UTF-8";
    private static final String SECRET_KEY = "1234234234234112";

    /**
    * AES Decrypt Method
    *
     * @param ciphertext the text need to decrypt
     * @return cleartext
    * */
    public static String decrypt(String ciphertext) {
        byte[] buffer;
        byte[] bytes = Base64.getDecoder().decode(ciphertext);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKeySpec = new SecretKeySpec(AESUtil.SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,secretKeySpec,ivParameterSpec);
            buffer = cipher.doFinal(bytes);
            return new String(buffer,ENCODING);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES Encrypt Method
     *
     * @param cleartext the text need to decrypt
     * @return ciphertext
     * */
    public static String encrypt(String cleartext){
        try{
            byte[] raw = AESUtil.SECRET_KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(AESUtil.IV.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivParameterSpec);
            byte[] bytes = cipher.doFinal(cleartext.getBytes(StandardCharsets.UTF_8));
            return new BASE64Encoder().encode(bytes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

 Test class:

The result is as follows: 

Start the service, we use postman to verify 

The introductory text ahead is excerpted from Zhihu: Basics of Cryptography: AES Encryption Algorithm-Knowledge

What is AES encryption? Detailed explanation of the principle process of AES encryption algorithm-Knowledge 

The original code is not easy to type, thank you for your attention

Guess you like

Origin blog.csdn.net/Lee_92/article/details/131087876