[Java implements AES encryption and decryption]

This article mainly introduces AES encryption and decryption using Java to realize encryption. AES is the most common symmetric encryption algorithm. The symmetric encryption algorithm uses the same key for encryption and decryption. Friends who need it can refer to the following

First of all, our county has a general understanding of the encryption algorithm, as shown in the following figure:
insert image description here
Then let’s understand AES:
AES: Advanced Encryption Standard (Advanced Encryption Standard) is a block encryption standard adopted by the US federal government, and it is currently the most popular symmetric Encryption Algorithm.

Not much to say, let's take a look at its miscellaneous uses.

Use Java and Vue to realize the complete code example of transmitting information of AES encryption algorithm.

In Vue, Vue encrypts:

/**
 * 工具类
 */
import Vue from 'vue'
import CryptoJS from 'crypto-js'
let keyStr = "*********123";//加密密钥
let ivStr  = "*********456";//矢量
 
//加密
export function aes_encrypt(word){
    
     
  
    var key  = CryptoJS.enc.Utf8.parse(keyStr);
	var iv   = CryptoJS.enc.Utf8.parse(ivStr);
    // var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(word, key, {
    
    
		iv:iv,
		mode:CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}
 
//解密  
export function aes_decrypt(word){
    
      
  
    var key  = CryptoJS.enc.Utf8.parse(keyStr);//
	var iv   = CryptoJS.enc.Utf8.parse(ivStr);
	// const restoreBase64 = word.replace(/\-/g,'+').replace(/_/g,'/');
	var restoreBase64=word.replace(/[\r\n]/g,'');
 
    var decrypt = CryptoJS.AES.decrypt(restoreBase64, key, {
    
    
		iv:iv,
		mode:CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

Java decryption:

package com.qiyuan.qyframe.base.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;

/**
 * @Author 
 * @Create 2023/7/10
 */

@Slf4j
public class AESUtil {
    
    
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    /**
     * AES加密
     *
     * @param content 明文
     * @param key     秘钥
     * @return
     * @throws Exception
     */


    public static String encrypt(Object content, String key) throws Exception {
    
    
        String s ="";
        //判断content是否为字符串
        if(content instanceof String){
    
    
            s=content.toString();
        }else {
    
    
            s = JSONUtil.parse(content).toString();
        }
        // 将返回的加密过的 byte[] 转换成Base64编码字符串 !!!!很关键
        return base64ToString(AES_ECB_Encrypt(s.getBytes(), key.getBytes()));
    }

    /**
     * AES解密
     *
     * @param content Base64编码的密文
     * @param key     秘钥
     * @return
     * @throws Exception
     */
    public static Object decrypt(String content, String key,String iv) {
    
    
        // stringToBase64() 将 Base64编码的字符串转换成 byte[] !!!与base64ToString()配套使用
        try {
    
    
            byte[] base64 = stringToBase64(content);
            byte[] bytes = AES_ECB_Decrypt(base64, key.getBytes(),iv.getBytes());
            String result = new String(bytes);
            String s = result.replaceAll("\"", "");
            //判断解密出来的数据是字符串还是json
            if(s.startsWith("{") && s.endsWith("}")){
    
    
                JSON parse = JSONUtil.parse(s);
                return parse;
            }else{
    
    
                return s;
            }
        } catch (Exception e) {
    
    
            log.info("AES解密出错!!!");
            e.printStackTrace();
        }

        return null;
    }

    private static byte[] AES_ECB_Encrypt(byte[] content, byte[] keyBytes) {
    
    
        try {
    
    
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding","BC");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] AES_ECB_Decrypt(byte[] content, byte[] keyBytes,byte[] ivByte) {
    
    
        try {
    
    
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            Key sKeySpec = new SecretKeySpec(keyBytes, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return null;
    }
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
    
    
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

    /**
     * 字符串装换成 Base64
     */

    public static byte[] stringToBase64(String key) throws Exception {
    
    
        return Base64.decodeBase64(key.getBytes());
    }

    /**
     * Base64装换成字符串
     */
    public static String base64ToString(byte[] key) throws Exception {
    
    
        return new Base64().encodeToString(key);
    }





}

Guess you like

Origin blog.csdn.net/qq_39236283/article/details/131654354