[Javascript]实现对称加解密AES/CBC/PKCS5PADDING

2021-04-15 2315点热度 0人点赞 0条评论

AES/CBC/PKCS5PADDING 加解密的Java实现(加解密结果和Javascript版本互通),请看我的博客:https://blog.terrynow.com/2021/04/14/java-tool-aes-cbc-pkcs5padding-implement/

Python版本的实现(加解密结果同样和本篇互通),请查看这篇:https://blog.terrynow.com/2021/04/16/python-tool-aes-cbc-pkcs5padding-implement/

Javascript实现对称加解密AES,我们用到的是github上开源的库aes-js

引入AES-JS:

Node.js

使用npm安装 aes-js:

npm install aes-js

如何调用:

var aesjs = require('aes-js');

浏览器

在浏览器中直接调用 aes-js:

<script type="text/javascript" src="https://cdn.rawgit.com/ricmoo/aes-js/e27b99df/index.js"></script>

或者直接到https://github.com/ricmoo/aes-js下载index.js后引入HTML

以下是JS下实现AES/CBC/PKCS5PADDING加解密的例子:

//AES加密,把source文本加密后转成十六进制文本
//测试source是:你好,输出:697e93390662d4ec94a2718fcc40de0b
function encryptToHexString(source) {
    var key = "sixteencharacter";//16字节长度key
    var iv = "1234567890ABCDEF";//16字节长度iv

    // or var keyBytes = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];
    var keyBytes = aesjs.utils.utf8.toBytes(key);
    var ivBytes = aesjs.utils.utf8.toBytes(iv);

    var aesCbc = new aesjs.ModeOfOperation.cbc(keyBytes, ivBytes);
    var textBytes = aesjs.utils.utf8.toBytes(source);
    var padded = aesjs.padding.pkcs7.pad(textBytes);
    var encryptedBytes = aesCbc.encrypt(padded);
    return aesjs.utils.hex.fromBytes(encryptedBytes);
}

//AES解密,把十六进制密文source解密
//测试source是:697e93390662d4ec94a2718fcc40de0b,输出:你好
decryptFromHexString: function(source) {
    var key = "sixteencharacter";
    var iv = "1234567890ABCDEF";

    var keyBytes = aesjs.utils.utf8.toBytes(key);
    var ivBytes = aesjs.utils.utf8.toBytes(iv);

    var aesCbc = new aesjs.ModeOfOperation.cbc(keyBytes, ivBytes);
    var encryptedBytes = aesjs.utils.hex.toBytes(source);
    var decryptedBytes = aesCbc.decrypt(encryptedBytes);
    return aesjs.utils.utf8.fromBytes(decryptedBytes);
}

//如果需要把加解密的bytes转成base64 encode url,可以使用如下方法
function base64EncodeURL(byteArray) {
  return btoa(Array.from(new Uint8Array(byteArray)).map(val => {
    return String.fromCharCode(val);
  }).join('')).replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
}

function base64DecodeURL(b64urlstring) {
  return new Uint8Array(atob(b64urlstring.replace(/-/g, '+').replace(/_/g, '/')).split('').map(val => {
    return val.charCodeAt(0);
  }));
}

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论