AES前端加密,后端Java解密

本文最后更新于2022.05.14-17:14,某些文章具有时效性,若有错误或已失效,请在下方留言或联系涛哥

一般版

导入加密使用的js文件

<%--加密使用的包--%> 
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script> 
<script src="https://cdn.bootcdn.net/ajax/libs/aes-js/3.1.2/index.min.js"></script>

前端加密和解密 js代码如下

// AES 加密,AES-128, AES-192, AES-256
// AES-128: key和iv都是16个字节,16*8=128bit
// AES-192: key和iv都是24个字节,24*8=128bit
// AES-256: key和iv都是32个字节,32*8=128bit
// iv 似乎一般都是纯数字
// 例如:AES_encrypt_CBC('需要加密的内容', '1234567890123456', '1234567890654321');
function AES_CBC_encrypt(message, key, iv) {
    // utf8字符串—>WordArray对象,WordArray是一个保存32位整数的数组,相当于转成了二进制
    let keyHex = CryptoJS.enc.Utf8.parse(key); //
    let ivHex = CryptoJS.enc.Utf8.parse(iv);
    let messageHex = CryptoJS.enc.Utf8.parse(message);
    let encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();// base64结果
    //return encrypted.ciphertext.toString();   // 二进制结果
}
// AES CBC模式解密
function AES_CBC_decrypt(messageBase64, key, iv) {
    // 如果加密后没有转成base64,那么先要转成base64再传入
    //let encryptedHexStr = CryptoJS.enc.Hex.parse(word);   // 从二进制文本转成二进制
    //messageBase64 = CryptoJS.enc.Base64.stringify(encryptedHexStr);    // 转成base64
    let keyHex = CryptoJS.enc.Utf8.parse(key);
    let ivHex = CryptoJS.enc.Utf8.parse(iv);
    let decrypt = CryptoJS.AES.decrypt(messageBase64, keyHex, {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}
// AES ECB模式加密,没有iv
function AES_ECB_encrypt(message, key) {
    // utf8字符串—>WordArray对象,WordArray是一个保存32位整数的数组,相当于转成了二进制
    let keyHex = CryptoJS.enc.Utf8.parse(key); //
    let messageHex = CryptoJS.enc.Utf8.parse(message);
    let encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();// base64结果
    //return encrypted.ciphertext.toString();   // 二进制结果
}
// AES ECB模式解密
function AES_ECB_decrypt(messageBase64, key) {
    // 如果加密后没有转成base64,那么先要转成base64再传入
    //let encryptedHexStr = CryptoJS.enc.Hex.parse(word);   // 从二进制文本转成二进制
    //messageBase64 = CryptoJS.enc.Base64.stringify(encryptedHexStr);    // 转成base64
    let keyHex = CryptoJS.enc.Utf8.parse(key);
    let decrypt = CryptoJS.AES.decrypt(messageBase64, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

Java后端加密和解密

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.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;


/**
 * @author ybakiame
 * @className AESCrypt
 * @description AES加解密工具,AES-128: key和iv都是16个字节,16*8=128bit,java似乎只支持AES-128
 * @createTime 2021/11/15 21:19
 */
public class AESCrypt {
    /**
     * AES CBC 加密
     * @param message 需要加密的字符串
     * @param key   密匙
     * @param iv    IV,需要和key长度相同
     * @return  返回加密后密文,编码为base64
     */
    public static String encryptCBC(String message, String key, String iv) {
        final String cipherMode = "AES/CBC/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            byte[] content = new byte[0];
            content = message.getBytes(charsetName);
            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
            //
            byte[] ivByte = iv.getBytes(charsetName);
            IvParameterSpec ivSpec = new IvParameterSpec(ivByte);

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] data = cipher.doFinal(content);
            final Base64.Encoder encoder = Base64.getEncoder();
            final String result = encoder.encodeToString(data);
            return result;
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * AES CBC 解密
     * @param messageBase64 密文,base64编码
     * @param key   密匙,和加密时相同
     * @param iv    IV,需要和key长度相同
     * @return  解密后数据
     */
    public static String decryptCBC(String messageBase64, String key, String iv) {
        final String cipherMode = "AES/CBC/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] messageByte = decoder.decode(messageBase64);

            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
            //
            byte[] ivByte = iv.getBytes(charsetName);
            IvParameterSpec ivSpec = new IvParameterSpec(ivByte);

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] content = cipher.doFinal(messageByte);
            String result = new String(content, charsetName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * AES ECB 加密
     * @param message 需要加密的字符串
     * @param key   密匙
     * @return  返回加密后密文,编码为base64
     */
    public static String encryptECB(String message, String key) {
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            byte[] content = new byte[0];
            content = message.getBytes(charsetName);
            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] data = cipher.doFinal(content);
            final Base64.Encoder encoder = Base64.getEncoder();
            final String result = encoder.encodeToString(data);
            return result;
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * AES ECB 解密
     * @param messageBase64 密文,base64编码
     * @param key   密匙,和加密时相同
     * @return  解密后数据
     */
    public static String decryptECB(String messageBase64, String key) {
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] messageByte = decoder.decode(messageBase64);

            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] content = cipher.doFinal(messageByte);
            String result = new String(content, charsetName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        String content = "测试8";
        String encrypt = AESCrypt.encryptECB(content,"abcdefgabcdefg12");
        String decrypt = AESCrypt.decryptECB(encrypt, "abcdefgabcdefg12");
        System.out.println(content);
        System.out.println(encrypt);
        System.out.println(decrypt);
    }
}

精简版

前端加密

    let aaa = "${key}";
    // AES ECB模式加密,没有iv
    function AES_ECB_encrypt(message, key) {
        // utf8字符串—>WordArray对象,WordArray是一个保存32位整数的数组,相当于转成了二进制
        let keyHex = CryptoJS.enc.Utf8.parse(key); //
        let messageHex = CryptoJS.enc.Utf8.parse(message);
        let encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();// base64结果
        //return encrypted.ciphertext.toString();   // 二进制结果
    }

Java后端解密

package com.xxgc.spring.util;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESCrypt {
    public static String KEY = "12345678abcdefgh";
    
    public static String decryptECB(String messageBase64, String key) {
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] messageByte = decoder.decode(messageBase64);

            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] content = cipher.doFinal(messageByte);
            String result = new String(content, charsetName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
阅读剩余
THE END