crypt.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import CryptoJS from 'crypto-js'
  2. class CryptToJS {
  3. private crypt: typeof CryptoJS
  4. private secret: string
  5. private key: CryptoJS.lib.WordArray
  6. private iv: CryptoJS.lib.WordArray
  7. constructor() {
  8. this.crypt = CryptoJS
  9. this.secret = 'Believe in yourself.'
  10. this.key = CryptoJS.enc.Utf8.parse(this.secret)
  11. this.iv = CryptoJS.enc.Utf8.parse(this.secret.slice(0, 16))
  12. }
  13. public encrypt(text: string): string {
  14. const encrypted = this.crypt.AES.encrypt(text, this.key, {
  15. iv: this.iv,
  16. mode: CryptoJS.mode.CBC,
  17. padding: CryptoJS.pad.Pkcs7
  18. })
  19. return encrypted.toString()
  20. }
  21. public decrypt(text: string): string {
  22. if (!text) return ''
  23. const decrypted = this.crypt.AES.decrypt(text, this.key, {
  24. iv: this.iv,
  25. mode: CryptoJS.mode.CBC,
  26. padding: CryptoJS.pad.Pkcs7
  27. })
  28. return decrypted.toString(CryptoJS.enc.Utf8)
  29. }
  30. }
  31. export default new CryptToJS()