原生js的RSA和AES加密解密算法
更新時(shí)間:2016年10月08日 10:53:31 投稿:lijiao
這篇文章主要為大家詳細(xì)介紹了原生js的RSA和AES加密解密算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了js中RSA和AES加密解密詳細(xì)代碼,供大家參考,具體內(nèi)容如下
<!doctype html>
<html>
<head>
<meta charset='UTF-8'>
</head>
<body>
<div class='test'></div>
<script type="text/javascript">
function encrypt(data, keyJSON){
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>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS通過ajax動態(tài)讀取xml文件內(nèi)容的方法
這篇文章主要介紹了JS通過ajax動態(tài)讀取xml文件內(nèi)容的方法,實(shí)例分析了Ajax操作XML文件的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
基于JavaScript實(shí)現(xiàn)無限加載瀑布流
這篇文章主要為大家詳細(xì)介紹了基于JavaScript實(shí)現(xiàn)無限加載瀑布流,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Android中Okhttp3實(shí)現(xiàn)上傳多張圖片同時(shí)傳遞參數(shù)
本篇文章主要介紹了Android中Okhttp3實(shí)現(xiàn)上傳多張圖片同時(shí)傳遞參數(shù) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
詳談js中標(biāo)準(zhǔn)for循環(huán)與foreach(for in)的區(qū)別
下面小編就為大家?guī)硪黄斦刯s中標(biāo)準(zhǔn)for循環(huán)與foreach(for in)的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
在knockoutjs 上自己實(shí)現(xiàn)的flux(實(shí)例講解)
下面小編就為大家分享一篇在knockoutjs 上自己實(shí)現(xiàn)的flux方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
利用JavaScript實(shí)現(xiàn)ISO周日歷
周日歷是日常生活中不常用到的歷法系統(tǒng),一般用于政府、商務(wù)的會計(jì)年度或者學(xué)校教學(xué)日歷中。本文將利用JavaScript制作個簡單的周日歷,感興趣的可嘗試一下2022-07-07

