当前位置:Gxlcms > JavaScript > 原生js的RSA和AES加密解密算法

原生js的RSA和AES加密解密算法

时间:2021-07-01 10:21:17 帮助过:14人阅读

本文实例为大家分享了js中RSA和AES加密解密详细代码,供大家参考,具体内容如下

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset='UTF-8'>
  5. </head>
  6. <body>
  7. <div class='test'></div>
  8. <script type="text/javascript">
  9. function encrypt(data, keyJSON){
  10. var data = new TextEncoder("UTF-8").encode(data);
  11. var randomsKeys = geneRandomHexStr(64); // 128 bit keys
  12. var encryptedKey = hexStringToUint8Array(randomsKeys);
  13. var aesAlgo = {name: 'aes-cbc', iv: hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
  14. return crypto.subtle.importKey("jwk", keyJSON, {name: "rsa-oaep", hash: {name: "sha-256"}},true, ['encrypt'])
  15. .then(function(publicKey){
  16. return crypto.subtle.encrypt({name: "rsa-oaep"}, publicKey, encryptedKey);
  17. }).then(function(res){
  18. encryptedKey = bytesToHexString(res)
  19. // use aes to encrypt data
  20. // import aes key
  21. return crypto.subtle.importKey('raw',
  22. hexStringToUint8Array(randomsKeys) , aesAlgo, false, ['encrypt', 'decrypt']);
  23. }).then(function(result){
  24. // use aes to encode
  25. return crypto.subtle.encrypt(aesAlgo,
  26. result, data);
  27. }).then(function(encryptedData){
  28. return Promise.resolve({
  29. 'encrypted': bytesToHexString(encryptedData),
  30. 'encryptedKey': encryptedKey,
  31. });
  32. });
  33. //console.log(new TextDecoder("UTF-8").decode(data));
  34. // use server public key to encrypt
  35. }
  36. function decrypt(data, keyJSON){
  37. // use local private key to decrypt
  38. var encryptedKey = new hexStringToUint8Array(data.encryptedKey);
  39. var encryptedData = new hexStringToUint8Array(data.encrypted);
  40. var aesAlgo = {name: 'aes-cbc', iv: hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
  41. // decrypt key
  42. return crypto.subtle.importKey('jwk', keyJSON, {name: "rsa-oaep", hash: {name: "sha-256"}}, true,
  43. ['decrypt']).then(function(privateKey){
  44. return crypto.subtle.decrypt({name: 'rsa-oaep'}, privateKey, encryptedKey);
  45. }).then(function(decryptedKey){
  46. // import aes key
  47. return crypto.subtle.importKey('raw',
  48. decryptedKey, aesAlgo, false, ['encrypt', 'decrypt']);
  49. }).catch(function(){
  50. console.error("decrypt error");
  51. }).then(function(result){
  52. // decode encrypted data
  53. return crypto.subtle.decrypt(aesAlgo, result, encryptedData);
  54. }).then(function(data){
  55. return Promise.resolve(new TextDecoder("UTF-8").decode(new Uint8Array(data)));
  56. })
  57. }
  58. function createNewUserKey(){
  59. var algorithmKeyGen = {
  60. name: "RSA-OAEP",
  61. hash: {name: "sha-256"},
  62. // RsaKeyGenParams
  63. modulusLength: 2048,
  64. publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537
  65. };
  66. var nonExtractable = false;
  67. var publicKey = "";
  68. var privateKey = "";
  69. var keyPairs = "";
  70. return crypto.subtle.generateKey(algorithmKeyGen, true, ['encrypt', 'decrypt']).then(function(result) {
  71. // gene key pair
  72. keyPairs = result;
  73. return Promise.all([crypto.subtle.exportKey("jwk", keyPairs.publicKey),
  74. crypto.subtle.exportKey("jwk", keyPairs.privateKey)]);
  75. })
  76. }
  77. function _arrayBufferToBase64( buffer ) {
  78. var binary = '';
  79. var bytes = new Uint8Array( buffer );
  80. var len = bytes.byteLength;
  81. for (var i = 0; i < len; i++) {
  82. binary += String.fromCharCode( bytes[ i ] );
  83. }
  84. return window.btoa( binary );
  85. }
  86. function hexStringToUint8Array(hexString) {
  87. if (hexString.length % 2 != 0)
  88. throw "Invalid hexString";
  89. var arrayBuffer = new Uint8Array(hexString.length / 2);
  90. for (var i = 0; i < hexString.length; i += 2) {
  91. var byteValue = parseInt(hexString.substr(i, 2), 16);
  92. if (byteValue == NaN)
  93. throw "Invalid hexString";
  94. arrayBuffer[i/2] = byteValue;
  95. }
  96. return arrayBuffer;
  97. }
  98. function bytesToHexString(bytes) {
  99. if (!bytes)
  100. return null;
  101. bytes = new Uint8Array(bytes);
  102. var hexBytes = [];
  103. for (var i = 0; i < bytes.length; ++i) {
  104. var byteString = bytes[i].toString(16);
  105. if (byteString.length < 2)
  106. byteString = "0" + byteString;
  107. hexBytes.push(byteString);
  108. }
  109. return hexBytes.join("");
  110. }
  111. function geneRandomHexStr(length){
  112. var text = "";
  113. var possible = "0123456789abcdef";
  114. for( var i=0; i < length; i++ )
  115. text += possible.charAt(Math.floor(Math.random() * possible.length));
  116. return text;
  117. }
  118. createNewUserKey().then(function(keyPairs){
  119. encrypt("this is origin text", keyPairs[0]).then(function(res){
  120. console.log('public', JSON.stringify(keyPairs[0]));
  121. console.log('private', JSON.stringify(keyPairs[1]));
  122. decrypt(res, keyPairs[1]).then(function(decrypted){
  123. console.log('decrypted', decrypted);
  124. });
  125. });
  126. })
  127. </script>
  128. </body>
  129. </html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行