cipher.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { encrypt, decrypt } from 'crypto-js/aes';
  2. import UTF8, { parse } from 'crypto-js/enc-utf8';
  3. import pkcs7 from 'crypto-js/pad-pkcs7';
  4. import ECB from 'crypto-js/mode-ecb';
  5. import md5 from 'crypto-js/md5';
  6. import Base64 from 'crypto-js/enc-base64';
  7. export interface EncryptionParams {
  8. key: string;
  9. iv: string;
  10. }
  11. export class AesEncryption {
  12. private key;
  13. private iv;
  14. constructor(opt: Partial<EncryptionParams> = {}) {
  15. const { key, iv } = opt;
  16. if (key) {
  17. this.key = parse(key);
  18. }
  19. if (iv) {
  20. this.iv = parse(iv);
  21. }
  22. }
  23. get getOptions() {
  24. return {
  25. mode: ECB,
  26. padding: pkcs7,
  27. iv: this.iv,
  28. };
  29. }
  30. encryptByAES(cipherText: string) {
  31. return encrypt(cipherText, this.key, this.getOptions).toString();
  32. }
  33. decryptByAES(cipherText: string) {
  34. return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
  35. }
  36. }
  37. export function encryptByBase64(cipherText: string) {
  38. return UTF8.parse(cipherText).toString(Base64);
  39. }
  40. export function decodeByBase64(cipherText: string) {
  41. return Base64.parse(cipherText).toString(UTF8);
  42. }
  43. export function encryptByMd5(password: string) {
  44. return md5(password).toString();
  45. }