crypto.ts 639 B

123456789101112131415161718192021222324252627
  1. import CryptoJS from 'crypto-js';
  2. export class Crypto<T extends object> {
  3. /** Secret */
  4. secret: string;
  5. constructor(secret: string) {
  6. this.secret = secret;
  7. }
  8. encrypt(data: T): string {
  9. const dataString = JSON.stringify(data);
  10. const encrypted = CryptoJS.AES.encrypt(dataString, this.secret);
  11. return encrypted.toString();
  12. }
  13. decrypt(encrypted: string) {
  14. const decrypted = CryptoJS.AES.decrypt(encrypted, this.secret);
  15. const dataString = decrypted.toString(CryptoJS.enc.Utf8);
  16. try {
  17. return JSON.parse(dataString) as T;
  18. } catch {
  19. // avoid parse error
  20. return null;
  21. }
  22. }
  23. }