关于aes加密

aes加密有几种模式:CBC,AES-128bit, Pkcs7补码方式(后台有可能是PKCS5Padding,是一样的),安卓和ios的key密钥对长度没有要求,但是前端web的密钥和偏移量必须是16位的,才能与java后台对上,前端代码如下

//aes加密
function encrypt(word) {
    var key = CryptoJS.enc.Utf8.parse("1234567890000000"); //16位
    var iv = CryptoJS.enc.Utf8.parse("1234567890000000");
    var encrypted = '';
    if (typeof(word) == 'string') {
        var srcs = CryptoJS.enc.Utf8.parse(word);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
    } else if (typeof(word) == 'object') {//对象格式的转成json字符串
        data = JSON.stringify(word);
        var srcs = CryptoJS.enc.Utf8.parse(data);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
    }
    return encrypted.ciphertext.toString();
}
// aes解密
function decrypt(word) {
    var key = CryptoJS.enc.Utf8.parse("1234567890000000"); 
    var iv = CryptoJS.enc.Utf8.parse("1234567890000000");
    var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    var decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

需要下载CryptoJS的包,下载:https://code.google.com/archive/p/crypto-js/downloads

posted @ 2019-05-21 20:29  极客小乌龟  阅读(746)  评论(0编辑  收藏  举报