encryptor.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. var crypto = require('crypto');
  3. var Encryptor = {
  4. /**
  5. * Calculate a hash of the concatenated buffers with the given algorithm.
  6. * @param {string} algorithm - The hash algorithm.
  7. * @returns {Buffer} The hash
  8. */
  9. hash: function hash(algorithm) {
  10. var hash = crypto.createHash(algorithm);
  11. for (var _len = arguments.length, buffers = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12. buffers[_key - 1] = arguments[_key];
  13. }
  14. hash.update(Buffer.concat(buffers));
  15. return hash.digest();
  16. },
  17. /**
  18. * Convert a password into an encryption key
  19. * @param {string} password - The password
  20. * @param {string} hashAlgorithm - The hash algoritm
  21. * @param {string} saltValue - The salt value
  22. * @param {number} spinCount - The spin count
  23. * @param {number} keyBits - The length of the key in bits
  24. * @param {Buffer} blockKey - The block key
  25. * @returns {Buffer} The encryption key
  26. */
  27. convertPasswordToHash: function convertPasswordToHash(password, hashAlgorithm, saltValue, spinCount) {
  28. hashAlgorithm = hashAlgorithm.toLowerCase();
  29. var hashes = crypto.getHashes();
  30. if (hashes.indexOf(hashAlgorithm) < 0) {
  31. throw new Error("Hash algorithm '".concat(hashAlgorithm, "' not supported!"));
  32. } // Password must be in unicode buffer
  33. var passwordBuffer = Buffer.from(password, 'utf16le'); // Generate the initial hash
  34. var key = this.hash(hashAlgorithm, Buffer.from(saltValue, 'base64'), passwordBuffer); // Now regenerate until spin count
  35. for (var i = 0; i < spinCount; i++) {
  36. var iterator = Buffer.alloc(4); // this is the 'special' element of Excel password hashing
  37. // that stops us from using crypto.pbkdf2()
  38. iterator.writeUInt32LE(i, 0);
  39. key = this.hash(hashAlgorithm, key, iterator);
  40. }
  41. return key.toString('base64');
  42. },
  43. /**
  44. * Generates cryptographically strong pseudo-random data.
  45. * @param size The size argument is a number indicating the number of bytes to generate.
  46. */
  47. randomBytes: function randomBytes(size) {
  48. return crypto.randomBytes(size);
  49. }
  50. };
  51. module.exports = Encryptor;
  52. //# sourceMappingURL=encryptor.js.map