cipher.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { encrypt, decrypt } from 'crypto-js/aes';
  2. import { parse } from 'crypto-js/enc-utf8';
  3. import pkcs7 from 'crypto-js/pad-pkcs7';
  4. import md5 from 'crypto-js/md5';
  5. import UTF8 from 'crypto-js/enc-utf8';
  6. import Base64 from 'crypto-js/enc-base64';
  7. import * as CryptoJS from 'crypto-js';
  8. export interface EncryptionParams {
  9. key: string;
  10. iv: string;
  11. }
  12. export class AesEncryption {
  13. key;
  14. iv;
  15. constructor(opt: Partial<EncryptionParams> = {}) {
  16. const { key, iv } = opt;
  17. if (key) {
  18. this.key = parse(key);
  19. }
  20. if (iv) {
  21. this.iv = parse(iv);
  22. }
  23. }
  24. get getOptions() {
  25. return {
  26. mode: CryptoJS.mode.CBC,
  27. padding: pkcs7,
  28. iv: this.iv,
  29. };
  30. }
  31. encryptByAES(cipherText: string) {
  32. return encrypt(cipherText, this.key, this.getOptions).toString();
  33. }
  34. decryptByAES(cipherText: string) {
  35. return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
  36. }
  37. // 将 Uint8Array 转换为 CryptoJS.lib.WordArray
  38. static uint8ArrayToWordArray(uint8Array: Uint8Array): CryptoJS.lib.WordArray {
  39. const words: number[] = [];
  40. for (let i = 0; i < uint8Array.length; i += 4) {
  41. let word = 0;
  42. for (let j = 0; j < 4 && i + j < uint8Array.length; j++) {
  43. word |= (uint8Array[i + j] & 0xff) << (24 - 8 * j);
  44. }
  45. words.push(word);
  46. }
  47. return CryptoJS.lib.WordArray.create(words, uint8Array.length);
  48. }
  49. // 将 CryptoJS.lib.WordArray 转换为 Uint8Array
  50. static wordArrayToUint8Array(wordArray: CryptoJS.lib.WordArray): Uint8Array {
  51. const words = wordArray.words;
  52. const sigBytes = wordArray.sigBytes;
  53. const uint8Array = new Uint8Array(sigBytes);
  54. for (let i = 0; i < sigBytes; i++) {
  55. const byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  56. uint8Array[i] = byte;
  57. }
  58. return uint8Array;
  59. }
  60. }
  61. export function encryptByBase64(cipherText: string) {
  62. return UTF8.parse(cipherText).toString(Base64);
  63. }
  64. export function decodeByBase64(cipherText: string) {
  65. return Base64.parse(cipherText).toString(UTF8);
  66. }
  67. export function encryptByMd5(password: string) {
  68. return md5(password).toString();
  69. }