原生js的RSA和AES加密解密详解编程语言
2023-06-13 09:20:25 时间
var data = new TextEncoder("UTF-8").encode(data);
var randomsKeys = geneRandomHexStr(64); // 128 bit keys
var encryptedKey = hexStringToUint8Array(randomsKeys);
var aesAlgo = {name: aes-cbc, iv: hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
return crypto.subtle.importKey("jwk", keyJSON, {name: "rsa-oaep", hash: {name: "sha-256"}},true, [encrypt])
.then(function(publicKey){
return crypto.subtle.encrypt({name: "rsa-oaep"}, publicKey, encryptedKey);
}).then(function(res){
encryptedKey = bytesToHexString(res)
// use aes to encrypt data
// import aes key
return crypto.subtle.importKey(raw,
hexStringToUint8Array(randomsKeys) , aesAlgo, false, [encrypt, decrypt]);
}).then(function(result){
// use aes to encode
return crypto.subtle.encrypt(aesAlgo,
result, data);
}).then(function(encryptedData){
return Promise.resolve({
encrypted: bytesToHexString(encryptedData),
encryptedKey: encryptedKey,
});
});
//console.log(new TextDecoder("UTF-8").decode(data));
// use server public key to encrypt
function decrypt(data, keyJSON){
// use local private key to decrypt
var encryptedKey = new hexStringToUint8Array(data.encryptedKey);
var encryptedData = new hexStringToUint8Array(data.encrypted);
var aesAlgo = {name: aes-cbc, iv: hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
// decrypt key
return crypto.subtle.importKey(jwk, keyJSON, {name: "rsa-oaep", hash: {name: "sha-256"}}, true,
[decrypt]).then(function(privateKey){
return crypto.subtle.decrypt({name: rsa-oaep}, privateKey, encryptedKey);
}).then(function(decryptedKey){
// import aes key
return crypto.subtle.importKey(raw,
decryptedKey, aesAlgo, false, [encrypt, decrypt]);
}).catch(function(){
console.error("decrypt error");
}).then(function(result){
// decode encrypted data
return crypto.subtle.decrypt(aesAlgo, result, encryptedData);
}).then(function(data){
return Promise.resolve(new TextDecoder("UTF-8").decode(new Uint8Array(data)));
function createNewUserKey(){
var algorithmKeyGen = {
name: "RSA-OAEP",
hash: {name: "sha-256"},
// RsaKeyGenParams
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537
var nonExtractable = false;
var publicKey = "";
var privateKey = "";
var keyPairs = "";
return crypto.subtle.generateKey(algorithmKeyGen, true, [encrypt, decrypt]).then(function(result) {
// gene key pair
keyPairs = result;
return Promise.all([crypto.subtle.exportKey("jwk", keyPairs.publicKey),
crypto.subtle.exportKey("jwk", keyPairs.privateKey)]);
function _arrayBufferToBase64( buffer ) {
var binary = ;
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i len; i++) {
binary += String.fromCharCode( bytes[ i ] );
return window.btoa( binary );
function hexStringToUint8Array(hexString) {
if (hexString.length % 2 != 0)
throw "Invalid hexString";
var arrayBuffer = new Uint8Array(hexString.length / 2);
for (var i = 0; i hexString.length; i += 2) {
var byteValue = parseInt(hexString.substr(i, 2), 16);
if (byteValue == NaN)
throw "Invalid hexString";
arrayBuffer[i/2] = byteValue;
return arrayBuffer;
function bytesToHexString(bytes) {
if (!bytes)
return null;
bytes = new Uint8Array(bytes);
var hexBytes = [];
for (var i = 0; i bytes.length; ++i) {
var byteString = bytes[i].toString(16);
if (byteString.length 2)
byteString = "0" + byteString;
hexBytes.push(byteString);
return hexBytes.join("");
function geneRandomHexStr(length){
var text = "";
var possible = "0123456789abcdef";
for( var i=0; i length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
createNewUserKey().then(function(keyPairs){
encrypt("this is origin text", keyPairs[0]).then(function(res){
console.log(public, JSON.stringify(keyPairs[0]));
console.log(private, JSON.stringify(keyPairs[1]));
decrypt(res, keyPairs[1]).then(function(decrypted){
console.log(decrypted, decrypted);
});
});
/script
/body
/html
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8865.html
cgojava相关文章
- Fabric.js 使用纯色遮挡画布(前景色)
- 彻底理解js中的闭包
- 前端MD5加密——js-md5[通俗易懂]
- html如何只刷新页面指定,js控制页面刷新 JS刷新当前页面的几种方法总结
- 前端面试题 --- JS高阶和其他
- Vue.js – 引入外部 JS 文件
- JS设置定时器_js设置定时器
- 【JS 逆向百例】猿人学系列 web 比赛第二题:js 混淆 - 动态 cookie,详细剖析
- 如何使用jscythe并通过Node.js的Inspector机制执行任意JS代码
- Node.JS中调用JShaman接口,实现JS代码加密
- js实现md5加密详解编程语言
- 使用JS控制Oracle数据库的更新(js控制oracle更新)
- 数据库JavaScript 的 Oracle 数据库连接技术简介(js如何连接oracle)
- JS将文件传输至MySQL数据库(.js传文件至mysql)
- 从前端JS里请求Redis资源,搭建高性能应用(前端js请求redis)
- js实现的网站首页随机公告随机公告
- Discuz!5.0.0论坛程序中加入一段js代码,让会员点击下载附件前自动弹出提示窗口
- js中匿名函数的N种写法
- 兼容IE、FireFox、Chrome等浏览器的xml处理函数js代码
- Base64编码加密JS代码网页版
- 兼容IE和FF的图片上传前预览js代码
- JS简单实现文件上传实例代码(无需插件)
- js替代copy(示例代码)
- JS获取计算机mac地址以及IP的实现方法
- js和jquery使按钮失效为不可用状态的方法
- js加密解密字符串可自定义密码因子
- js加密压缩出现bug解决方案
- js实现正方形颜色从下往上升的效果