cipher.ts 1.2 KB

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