AES 后台加密 CryptoJS 前台解密demo

来源:互联网 发布:mmd undefined动作数据 编辑:程序博客网 时间:2024/06/05 21:02

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 != 0) {                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));            }            byte[] plaintext = new byte[plaintextLength];            System.arraycopy(dataBytes, 0, plaintext, 0, 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;        }      }
原创粉丝点击