alexx876

Untitled

Jan 28th, 2022
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. var crypto = require('crypto');
  2. var CIPHER_ALGORITHM = 'aes-256-ctr';
  3.  
  4. function decrypt(key, encrypted) {
  5. if (typeof key !== 'string' || !key) {
  6. throw new TypeError('Provided "key" must be a non-empty string');
  7. }
  8.  
  9. var isString = typeof encrypted === 'string';
  10. var isBuffer = Buffer.isBuffer(encrypted);
  11. if (!(isString || isBuffer) || (isString && !encrypted) || (isBuffer && !Buffer.byteLength(encrypted))) {
  12. throw new TypeError('Provided "encrypted" must be a non-empty string or buffer');
  13. }
  14.  
  15. var sha256 = crypto.createHash('sha256');
  16. sha256.update(key);
  17.  
  18. var input = encrypted;
  19. if (isString) {
  20. input = Buffer.from(encrypted, 'base64');
  21.  
  22. if (input.length < 17) {
  23. throw new TypeError('Provided "encrypted" must decrypt to a non-empty string or buffer');
  24. }
  25. } else {
  26. if (Buffer.byteLength(encrypted) < 17) {
  27. throw new TypeError('Provided "encrypted" must decrypt to a non-empty string or buffer');
  28. }
  29. }
  30.  
  31. // Initialization Vector
  32. var iv = input.slice(0, 16);
  33. var decipher = crypto.createDecipheriv(CIPHER_ALGORITHM, sha256.digest(), iv);
  34.  
  35. var ciphertext = input.slice(16);
  36.  
  37. var output;
  38. if (isString) {
  39. output = decipher.update(ciphertext) + decipher.final();
  40. } else {
  41. output = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
  42. }
  43.  
  44. return output;
  45. }
Add Comment
Please, Sign In to add comment