crypto-js-adapter.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // utils/crypto-js-adapter.js
  2. // 适配微信小程序的 CryptoJS 工具
  3. import JSEncrypt from '@/components/jsencrypt/jsencrypt.min.js';
  4. // 引入 CryptoJS 核心文件
  5. import Core from '../crypto-js/core.js';
  6. import AES from '../crypto-js/aes.js';
  7. import Utf8 from '../crypto-js/enc-utf8.js';
  8. import Base64 from '../crypto-js/enc-base64.js';
  9. import Hex from '../crypto-js/enc-hex.js';
  10. // import CBC from '../crypto-js/mode-cbc.js';
  11. import CryptoJS from '../crypto-js/index.js'
  12. import Pkcs7 from '../crypto-js/pad-pkcs7.js';
  13. // 适配微信小程序的随机数生成器
  14. function wxGetRandomValues(length) {
  15. return new Promise((resolve, reject) => {
  16. wx.getRandomValues({
  17. length: length,
  18. success: (res) => {
  19. resolve(res);
  20. },
  21. fail: (err) => {
  22. reject(err);
  23. }
  24. });
  25. });
  26. }
  27. // 将ArrayBuffer转换为CryptoJS WordArray
  28. function arrayBufferToWordArray(arrayBuffer) {
  29. const uint8Array = new Uint8Array(arrayBuffer);
  30. console.log(uint8Array, '333')
  31. const words = [];
  32. for (let i = 0; i < uint8Array.length; i += 4) {
  33. let word = 0;
  34. for (let j = 0; j < 4; j++) {
  35. if (i + j < uint8Array.length) {
  36. word |= uint8Array[i + j] << (24 - j * 8);
  37. }
  38. }
  39. words.push(word);
  40. }
  41. return CryptoJS.lib.WordArray.create(words, uint8Array.length);
  42. }
  43. Core.lib.WordArray.random = async function(nBytes) {
  44. // 创建一个16字节的Uint8Array
  45. const res = await wxGetRandomValues(nBytes);
  46. console.log(res)
  47. const ivWordArray = arrayBufferToWordArray(res.randomValues);
  48. console.log(ivWordArray.words, '111')
  49. // 转换为十六进制字符串并截取前16字节(32个字符)
  50. const hexString = ivWordArray.toString();
  51. const ivValue = hexString.substring(0, 32);
  52. console.log(ivValue, hexString, '000')
  53. return hexString
  54. };
  55. /**
  56. * AES加密(使用CryptoJS)
  57. * @param {string} data 要加密的数据
  58. * @param {string} key 密钥
  59. * @param {string} iv 初始化向量(十六进制格式)
  60. * @returns {Promise<{encrypted: string, iv: string}>}
  61. */
  62. async function encrypt(data, key, iv = null) {
  63. try {
  64. // 生成随机IV(如果未提供)
  65. if (!iv) {
  66. iv = await Core.lib.WordArray.random(16);
  67. }
  68. // 执行加密
  69. const encrypted = AES.encrypt(
  70. JSON.stringify(data),
  71. CryptoJS.enc.Utf8.parse(key), {
  72. iv: CryptoJS.enc.Utf8.parse(iv),
  73. mode: CryptoJS.mode.CBC,
  74. padding: CryptoJS.pad.Pkcs7
  75. });
  76. return {
  77. encrypted: encrypted.toString(),
  78. iv: iv
  79. };
  80. } catch (error) {
  81. console.error('AES加密失败:', error);
  82. throw error;
  83. }
  84. }
  85. /**
  86. * AES解密(使用CryptoJS)
  87. * @param {string} encryptedData Base64格式的加密数据
  88. * @param {string} key 密钥
  89. * @param {string} iv 初始化向量(十六进制格式)
  90. * @returns {Promise<string>}
  91. */
  92. async function decrypt(encryptedData, key, iv) {
  93. try {
  94. const decrypted = AES.decrypt(encryptedData, CryptoJS.enc.Utf8.parse(iv), {
  95. iv: CryptoJS.enc.Utf8.parse(iv),
  96. mode: CryptoJS.mode.CBC,
  97. padding: Pkcs7
  98. });
  99. return decrypted.toString(Utf8);
  100. } catch (error) {
  101. console.error('AES解密失败:', error);
  102. throw error;
  103. }
  104. }
  105. /**
  106. * 生成随机密钥
  107. * @param {number} length 密钥长度(16, 24, 32)
  108. * @returns {Promise<string>}
  109. */
  110. async function generateKey(length = 32) {
  111. const randomKey = await Core.lib.WordArray.random(length);
  112. return Hex.stringify(randomKey);
  113. }
  114. /**
  115. * 生成随机IV
  116. * @returns {Promise<string>}
  117. */
  118. async function generateIV() {
  119. const randomIv = await Core.lib.WordArray.random(16);
  120. return Hex.stringify(randomIv);
  121. }
  122. // 生成密钥对
  123. function generateRSAKeyPair(){
  124. const keySize = parseInt(1024);
  125. const encryptor = new JSEncrypt({ default_key_size: keySize });
  126. encryptor.getKey();
  127. const publicKey = encryptor.getPublicKey();
  128. const privateKey = encryptor.getPrivateKey();
  129. console.log(publicKey,privateKey)
  130. }
  131. // rsa加密
  132. function rsaEncrypt(publicKey,data) {
  133. const encrypt = new JSEncrypt();
  134. encrypt.setPublicKey(publicKey);
  135. var time = +new Date();
  136. var str2 = data;
  137. return encrypt.encrypt(str2)
  138. }
  139. // ras解密
  140. function rsaDecrypt(PrivateKey, data) {
  141. const encrypt = new JSEncrypt();
  142. encrypt.setPrivateKey(PrivateKey);
  143. return encrypt.decrypt(data);
  144. }
  145. export default {
  146. encrypt,
  147. decrypt,
  148. generateKey,
  149. generateIV,
  150. generateRSAKeyPair,
  151. rsaEncrypt,
  152. rsaDecrypt
  153. };