原生js的RSA和AES加密解密算法
本文实例为大家分享了js中RSA和AES加密解密详细代码,供大家参考,具体内容如下
<!doctypehtml>
<html>
<head>
<metacharset='UTF-8'>
</head>
<body>
<divclass='test'></div>
<scripttype="text/javascript">
functionencrypt(data,keyJSON){
vardata=newTextEncoder("UTF-8").encode(data);
varrandomsKeys=geneRandomHexStr(64);//128bitkeys
varencryptedKey=hexStringToUint8Array(randomsKeys);
varaesAlgo={name:'aes-cbc',iv:hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
returncrypto.subtle.importKey("jwk",keyJSON,{name:"rsa-oaep",hash:{name:"sha-256"}},true,['encrypt'])
.then(function(publicKey){
returncrypto.subtle.encrypt({name:"rsa-oaep"},publicKey,encryptedKey);
}).then(function(res){
encryptedKey=bytesToHexString(res)
//useaestoencryptdata
//importaeskey
returncrypto.subtle.importKey('raw',
hexStringToUint8Array(randomsKeys),aesAlgo,false,['encrypt','decrypt']);
}).then(function(result){
//useaestoencode
returncrypto.subtle.encrypt(aesAlgo,
result,data);
}).then(function(encryptedData){
returnPromise.resolve({
'encrypted':bytesToHexString(encryptedData),
'encryptedKey':encryptedKey,
});
});
//console.log(newTextDecoder("UTF-8").decode(data));
//useserverpublickeytoencrypt
}
functiondecrypt(data,keyJSON){
//uselocalprivatekeytodecrypt
varencryptedKey=newhexStringToUint8Array(data.encryptedKey);
varencryptedData=newhexStringToUint8Array(data.encrypted);
varaesAlgo={name:'aes-cbc',iv:hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
//decryptkey
returncrypto.subtle.importKey('jwk',keyJSON,{name:"rsa-oaep",hash:{name:"sha-256"}},true,
['decrypt']).then(function(privateKey){
returncrypto.subtle.decrypt({name:'rsa-oaep'},privateKey,encryptedKey);
}).then(function(decryptedKey){
//importaeskey
returncrypto.subtle.importKey('raw',
decryptedKey,aesAlgo,false,['encrypt','decrypt']);
}).catch(function(){
console.error("decrypterror");
}).then(function(result){
//decodeencrypteddata
returncrypto.subtle.decrypt(aesAlgo,result,encryptedData);
}).then(function(data){
returnPromise.resolve(newTextDecoder("UTF-8").decode(newUint8Array(data)));
})
}
functioncreateNewUserKey(){
varalgorithmKeyGen={
name:"RSA-OAEP",
hash:{name:"sha-256"},
//RsaKeyGenParams
modulusLength:2048,
publicExponent:newUint8Array([0x01,0x00,0x01]),//Equivalentto65537
};
varnonExtractable=false;
varpublicKey="";
varprivateKey="";
varkeyPairs="";
returncrypto.subtle.generateKey(algorithmKeyGen,true,['encrypt','decrypt']).then(function(result){
//genekeypair
keyPairs=result;
returnPromise.all([crypto.subtle.exportKey("jwk",keyPairs.publicKey),
crypto.subtle.exportKey("jwk",keyPairs.privateKey)]);
})
}
function_arrayBufferToBase64(buffer){
varbinary='';
varbytes=newUint8Array(buffer);
varlen=bytes.byteLength;
for(vari=0;i<len;i++){
binary+=String.fromCharCode(bytes[i]);
}
returnwindow.btoa(binary);
}
functionhexStringToUint8Array(hexString){
if(hexString.length%2!=0)
throw"InvalidhexString";
vararrayBuffer=newUint8Array(hexString.length/2);
for(vari=0;i<hexString.length;i+=2){
varbyteValue=parseInt(hexString.substr(i,2),16);
if(byteValue==NaN)
throw"InvalidhexString";
arrayBuffer[i/2]=byteValue;
}
returnarrayBuffer;
}
functionbytesToHexString(bytes){
if(!bytes)
returnnull;
bytes=newUint8Array(bytes);
varhexBytes=[];
for(vari=0;i<bytes.length;++i){
varbyteString=bytes[i].toString(16);
if(byteString.length<2)
byteString="0"+byteString;
hexBytes.push(byteString);
}
returnhexBytes.join("");
}
functiongeneRandomHexStr(length){
vartext="";
varpossible="0123456789abcdef";
for(vari=0;i<length;i++)
text+=possible.charAt(Math.floor(Math.random()*possible.length));
returntext;
}
createNewUserKey().then(function(keyPairs){
encrypt("thisisorigintext",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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。