aes_util.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const CryptoJS = require('./aes.js'); //引用AES源码js
  2. const key = CryptoJS.enc.Utf8.parse("1546A43298451599"); //十六位十六进制数作为秘钥
  3. const iv = CryptoJS.enc.Utf8.parse('0102030405060708');//十六位十六进制数作为秘钥偏移量
  4. /**
  5. * aes cbc解密方法、需要iv偏移量
  6. */
  7. function AesDecrypt(word) {
  8. let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  9. let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  10. let decrypt = CryptoJS.AES.decrypt(srcs, key, {
  11. iv: iv,
  12. mode: CryptoJS.mode.CBC,
  13. padding: CryptoJS.pad.Pkcs7
  14. });
  15. let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  16. return decryptedStr.toString();
  17. }
  18. /**
  19. * aes cbc加密方法、需要iv偏移量
  20. */
  21. function AesEncrypt(word) {
  22. let srcs = CryptoJS.enc.Utf8.parse(word);
  23. let encrypted = CryptoJS.AES.encrypt(srcs, key, {
  24. iv: iv,
  25. mode: CryptoJS.mode.CBC,
  26. padding: CryptoJS.pad.Pkcs7
  27. });
  28. return encrypted.ciphertext.toString().toUpperCase();
  29. }
  30. /**
  31. * base64 加密方法
  32. */
  33. function Base64Encode(val) {
  34. let str = CryptoJS.enc.Utf8.parse(val);
  35. let base64 = CryptoJS.enc.Base64.stringify(str);
  36. return base64;
  37. }
  38. /**
  39. * base64 解密方法
  40. */
  41. function Base64Decode(val) {
  42. let words = CryptoJS.enc.Base64.parse(val);
  43. return words.toString(CryptoJS.enc.Utf8);
  44. }
  45. /**
  46. * aes ecb解密方法
  47. */
  48. function AesDecryptECB(word) {
  49. let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  50. let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  51. let decrypt = CryptoJS.AES.decrypt(srcs, key, {
  52. mode: CryptoJS.mode.ECB,
  53. padding: CryptoJS.pad.Pkcs7
  54. });
  55. let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  56. return decryptedStr.toString();
  57. }
  58. /**
  59. * aes ecb加密方法
  60. */
  61. function AesEncryptECB(word) {
  62. let srcs = CryptoJS.enc.Utf8.parse(word);
  63. let encrypted = CryptoJS.AES.encrypt(srcs, key, {
  64. mode: CryptoJS.mode.ECB,
  65. padding: CryptoJS.pad.Pkcs7
  66. });
  67. return encrypted.toString();
  68. }
  69. //暴露接口
  70. module.exports = {
  71. AesEncrypt,
  72. AesDecrypt,
  73. Base64Encode,
  74. Base64Decode,
  75. AesDecryptECB,
  76. AesEncryptECB,
  77. }