欢迎使用CSDN-markdown编辑器

来源:互联网 发布:东北师范大学网络教育招生简章 编辑:程序博客网 时间:2024/06/17 18:31

*
内容来源

node.js AES/ECB/PKCS5Padding 与其他语言的加密解密通用

*

一个AES块是16个字节,还差5个字节

AES/ECB/PKCS5Padding 斜线分隔的3部分分别是 算法/模式/填充量

AES算法的各种模式以及填充

看上面的列表可以知道aes加密后要么16要么32位(前提是大于16字节)

有些模式是不支持对于不满16字节字符串的加密,见上面列表最后一列 (不支持)

如果不满16字节且支持加密的模式,一定是有填充量的,就是不满16的字节用一个默认值来填充,直到它满16位后再加密.

AES/ECB/PKCS5Padding用这个模式来说一下.
node.js自带加密解密模块

如果你已经google找了半天关于node.js aes加密和其他语言不通用的时候.

第一检查你是不是用了下面的加密函数.
createCipher 加密函数不支持填充量,你需要的是 createCipheriv

可以看到多了一个 iv ,没错,这个方法与上一个不同的就是支持填充量 iv

直接见下面代码:

//data 是准备加密的字符串,key是你的密钥function encryption(data, key) {    var iv = "";    var clearEncoding = 'utf8';    var cipherEncoding = 'base64';    var cipherChunks = [];    var cipher = crypto.createCipheriv('aes-128-ecb', key, iv);    cipher.setAutoPadding(true);    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));    cipherChunks.push(cipher.final(cipherEncoding));    return cipherChunks.join('');}//data 是你的准备解密的字符串,key是你的密钥function decryption(data, key) {    var iv = "";    var clearEncoding = 'utf8';    var cipherEncoding = 'base64';    var cipherChunks = [];    var decipher = crypto.createDecipheriv('aes-128-ecb', key, iv);    decipher.setAutoPadding(true);    cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));    cipherChunks.push(decipher.final(clearEncoding));    return cipherChunks.join('');}      

上面的加密,解密函数 createCipheriv ,createDecipheriv
支持3个参数,最后一个参数iv就是填充量,我们使用了空字符串.

这样加密后和其他语言此模式下的加密串一致,相互解密也是没有问题的.

给文件AES加密,以及base64字符串转化为文件
//传文件路径和 加密 key, 返回加密base64字符串.

function encryption_file(file_path, key) {    var iv = "";    var clearEncoding = 'binary';    var cipherEncoding = 'base64';    var cipherChunks = [];    var cipher = crypto.createCipheriv('aes-128-ecb', key, iv);    cipher.setAutoPadding(true);    var buf = fs.readFileSync(file_path);    cipherChunks.push(cipher.update(buf, clearEncoding, cipherEncoding));    cipherChunks.push(cipher.final(cipherEncoding));    return cipherChunks.join('');}//传base64加密串和加密key ,返回直接数组,将字节数组转化为文件保存即可function decryption_file(file_base64, key) {    var iv = "";    var clearEncoding = 'binary';    var cipherEncoding = 'base64';    var cipherChunks = [];    var cipher = crypto.createCipheriv('aes-128-ecb', key, iv);    cipher.setAutoPadding(true);    cipherChunks.push(cipher.update(file_base64, cipherEncoding,clearEncoding));    cipherChunks.push(cipher.final(clearEncoding));    return cipherChunks;}