AES算法 前端JavaScript加密 后端Java解密

CryptoJS https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js

中文文档 https://cryptojs.gitbook.io/docs/

var AES = function () {
	const uuid32 = "00010203-04050607-08090A0B-0C0D0E0F".toString();
    const param = Array.from(uuid32.replaceAll("-", "").trim()).reduce(
        (prev, curr, idx) => {
            (0 === idx % 2 ? prev.key : prev.iv).unshift(curr);
            return prev;
        },
        {key: [], iv: []}
    );
    function sha1prng(key, length) {
        let hash = CryptoJS.SHA1(key);
        let result = CryptoJS.SHA1(hash).toString();
        return CryptoJS.enc.Hex.parse(result.substring(0, length));
    }
    const key = sha1prng(param.key.join(''), 32);
    const iv = CryptoJS.enc.Utf8.parse(param.iv.join(''));
    const cfg = {iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7};

    function Encrypt(text) {
        return CryptoJS.AES.encrypt(text, key, cfg).toString();
    }

    function Decrypt(text) {
        return CryptoJS.AES.decrypt(text, key, cfg).toString(CryptoJS.enc.Utf8);
    }

    return {
        Encrypt,
        Decrypt
    }
};
package xxx;

import javax.crypto.*;
import java.security.*;
import javax.crypto.spec.*;
import java.util.Base64;

public class AESEncryptor {

    /**
     * text: 加密内容
     * uuid32: 组织唯一识别码,32位字符串
     */
    public static String encrypt(String text, String uuid32) throws Exception {
        if (null != uuid32 && 0 < uuid32.length()) {
            uuid32 = uuid32.replace("-", "").trim();
            if (uuid32.length() == 32) {
                StringBuilder key = new StringBuilder();
                StringBuilder vector = new StringBuilder();
                char[] arr = uuid32.toCharArray();
                for (int i = 0; i < arr.length; i++) {
                    if (i % 2 == 0) {
                        key.insert(0, arr[i]);
                    } else {
                        vector.insert(0, arr[i]);
                    }
                }
                return encrypt(text, key.toString(), vector.toString());
            }
        }
        throw new Exception("uuid32 format error!");
    }

    /**
     * text: (base64编码格式)
     * uuid32: 组织唯一识别码,32位字符串
     */
    public static String decrypt(String text, String uuid32) throws Exception {
        if (null != uuid32 && 0 < uuid32.length()) {
            uuid32 = uuid32.replace("-", "").trim();
            if (uuid32.length() == 32) {
                StringBuilder key = new StringBuilder();
                StringBuilder vector = new StringBuilder();
                char[] arr = uuid32.toCharArray();
                for (int i = 0; i < arr.length; i++) {
                    if (i % 2 == 0) {
                        key.insert(0, arr[i]);
                    } else {
                        vector.insert(0, arr[i]);
                    }
                }
                return decrypt(text, key.toString(), vector.toString());
            }
        }
        throw new Exception("uuid32 format error!");
    }


    /**
     * text: 加密内容
     * key: 加密的盐,16位字符串
     * vector: 加密的向量,16位字符串
     */
    public static String encrypt(String text, String key, String vector) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes("utf-8"));
        Key secretKey= initKeyForAES(key);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] content = text.getBytes("utf-8");
        byte[] encrypted = cipher.doFinal(content);
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * content: 解密内容(base64编码格式)
     * key: 加密时使用的盐,16位字符串
     * vector: 加密时使用的向量,16位字符串
     */
    public static String decrypt(String text, String key, String vector) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        Key secretKey= initKeyForAES(key);
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes("utf-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] content = Base64.getDecoder().decode(text);
        byte[] encrypted = cipher.doFinal(content);
        return new String(encrypted,"utf-8");
    }

    private static Key initKeyForAES(String key) throws Exception {
        if (null == key || key.length() == 0) {
            throw new Exception("key not is null");
        }
        SecretKeySpec key2 = null;
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            key2 = new SecretKeySpec(enCodeFormat, "AES");
        } catch (NoSuchAlgorithmException ex) {
            throw new Exception(ex.getMessage());
        }
        return key2;
    }
}
posted @ 2023-04-20 10:28  祙子  阅读(440)  评论(0)    收藏  举报