Advertisement
nubooya

eas

Feb 23rd, 2022
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. const crypto = require('crypto');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const zlib = require('zlib');
  5.  
  6. const AppendInitVect = require('./AppendInitVect');
  7. // const getCipherKey = require('./getCipherKey');
  8.  
  9. function getCipherKey(password) {
  10. return crypto.createHash('sha256').update(password).digest();
  11. }
  12.  
  13. function encrypt({ file, password }) {
  14. // Generate a secure, pseudo random initialization vector.
  15. const initVect = crypto.randomBytes(16);
  16.  
  17. // Generate a cipher key from the password.
  18. const CIPHER_KEY = getCipherKey(password);
  19. const readStream = fs.createReadStream(file);
  20. const gzip = zlib.createGzip();
  21. const cipher = crypto.createCipheriv('aes256', CIPHER_KEY, initVect);
  22. const appendInitVect = new AppendInitVect(initVect);
  23. // Create a write stream with a different file extension.
  24. const writeStream = fs.createWriteStream(path.join(file + ".enc"));
  25.  
  26. readStream
  27. .pipe(gzip)
  28. .pipe(cipher)
  29. .pipe(appendInitVect)
  30. .pipe(writeStream);
  31. }
  32.  
  33. function decrypt({ file, password }) {
  34. // First, get the initialization vector from the file.
  35. const readInitVect = fs.createReadStream(file, { end: 15 });
  36.  
  37. let initVect;
  38. readInitVect.on('data', (chunk) => {
  39. initVect = chunk;
  40. });
  41.  
  42. // Once we’ve got the initialization vector, we can decrypt the file.
  43. readInitVect.on('close', () => {
  44. const cipherKey = getCipherKey(password);
  45. const readStream = fs.createReadStream(file, { start: 16 });
  46. const decipher = crypto.createDecipheriv('aes256', cipherKey, initVect);
  47. const unzip = zlib.createUnzip();
  48. const writeStream = fs.createWriteStream(file + '.unenc');
  49.  
  50. readStream
  51. .pipe(decipher)
  52. .pipe(unzip)
  53. .pipe(writeStream);
  54. });
  55. }
  56.  
  57. encrypt('./watermark.pdf', 'password')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement