cipher.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 ECB from 'crypto-js/mode-ecb';
  5. import md5 from 'crypto-js/md5';
  6. import UTF8 from 'crypto-js/enc-utf8';
  7. import Base64 from 'crypto-js/enc-base64';
  8. export interface EncryptionParams {
  9. key: string;
  10. iv: string;
  11. }
  12. export class AesEncryption {
  13. private key;
  14. private 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: ECB,
  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. }
  38. export function encryptByBase64(cipherText: string) {
  39. return UTF8.parse(cipherText).toString(Base64);
  40. }
  41. export function decodeByBase64(cipherText: string) {
  42. return Base64.parse(cipherText).toString(UTF8);
  43. }
  44. export function encryptByMd5(password: string) {
  45. return md5(password).toString();
  46. }