DerivePBKDF2Key.mjs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import Utils from "../Utils";
  8. import forge from "node-forge/dist/forge.min.js";
  9. /**
  10. * Derive PBKDF2 key operation
  11. */
  12. class DerivePBKDF2Key extends Operation {
  13. /**
  14. * DerivePBKDF2Key constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "Derive PBKDF2 key";
  19. this.module = "Ciphers";
  20. this.description = "PBKDF2 is a password-based key derivation function. It is part of RSA Laboratories' Public-Key Cryptography Standards (PKCS) series, specifically PKCS #5 v2.0, also published as Internet Engineering Task Force's RFC 2898.<br><br>In many applications of cryptography, user security is ultimately dependent on a password, and because a password usually can't be used directly as a cryptographic key, some processing is required.<br><br>A salt provides a large set of keys for any given password, and an iteration count increases the cost of producing keys from a password, thereby also increasing the difficulty of attack.<br><br>If you leave the salt argument empty, a random salt will be generated.";
  21. this.inputType = "string";
  22. this.outputType = "string";
  23. this.args = [
  24. {
  25. "name": "Passphrase",
  26. "type": "toggleString",
  27. "value": "",
  28. "toggleValues": ["UTF8", "Latin1", "Hex", "Base64"]
  29. },
  30. {
  31. "name": "Key size",
  32. "type": "number",
  33. "value": 128
  34. },
  35. {
  36. "name": "Iterations",
  37. "type": "number",
  38. "value": 1
  39. },
  40. {
  41. "name": "Hashing function",
  42. "type": "option",
  43. "value": ["SHA1", "SHA256", "SHA384", "SHA512", "MD5"]
  44. },
  45. {
  46. "name": "Salt",
  47. "type": "toggleString",
  48. "value": "",
  49. "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"]
  50. }
  51. ];
  52. }
  53. /**
  54. * @param {string} input
  55. * @param {Object[]} args
  56. * @returns {string}
  57. */
  58. run(input, args) {
  59. const passphrase = Utils.convertToByteString(args[0].string, args[0].option),
  60. keySize = args[1],
  61. iterations = args[2],
  62. hasher = args[3],
  63. salt = Utils.convertToByteString(args[4].string, args[4].option) ||
  64. forge.random.getBytesSync(keySize),
  65. derivedKey = forge.pkcs5.pbkdf2(passphrase, salt, iterations, keySize / 8, hasher.toLowerCase());
  66. return forge.util.bytesToHex(derivedKey);
  67. }
  68. }
  69. export default DerivePBKDF2Key;