天天看点

AES 后台加密 CryptoJS 前台解密demo

1.引入JS插件包

aes.js

core.js

enc-base64.js

mode-ecb-min.js

pad-nopadding-min.js

2.JS使用

function aesDecrypt(encrypted, key) {
            console.log("encrypted="+encrypted);
            var encrypted1 = CryptoJS.enc.Base64.parse(encrypted);
            var decrypted = CryptoJS.AES.decrypt(encrypted, CryptoJS.enc.Utf8.parse(key), {
                iv:CryptoJS.enc.Utf8.parse(key),
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.NoPadding
            });
            decrypted = CryptoJS.enc.Utf8.stringify(decrypted);// 转换为 utf8 字符串
            console.log("decrypted="+decrypted);
            return decrypted;
        }
           

3.java代码

/**
     * 向js页面 输出参数进行加密 (AES/CBC/NoPadding)
     * @param data  要加密的数据
     * @param key 加密key
     * @param iv 加密iv
     * @return 加密的结果
     * @throws Exception
     */
    public static String encryptJS(String data, String key, String iv){
        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes("UTF-8");//如果有中文,记得加密前的字符集
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != ) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, , plaintext, , dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return Base64.encodeBase64String(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }  
    }
           

继续阅读