2
0

keypair-generator.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2018 Scytl Secure Electronic Voting SA
  3. *
  4. * All rights reserved
  5. *
  6. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7. */
  8. /* jshint node:true */
  9. 'use strict';
  10. var KeyPair = require('./keypair');
  11. var Policy = require('scytl-cryptopolicy');
  12. var forge = require('node-forge');
  13. module.exports = KeyPairGenerator;
  14. /**
  15. * @class KeyPairGenerator
  16. * @classdesc The key pair generator API. To instantiate this object, use the
  17. * method {@link AsymmetricCryptographyService.newKeyPairGenerator}.
  18. * @hideconstructor
  19. * @param {Policy}
  20. * policy The cryptographic policy to use.
  21. * @param {SecureRandomService}
  22. * secureRandomService The secure random service to use.
  23. */
  24. function KeyPairGenerator(policy, secureRandomService) {
  25. /**
  26. * Generates a key pair to use for asymmetric cryptography operations.
  27. *
  28. * @function next
  29. * @memberof KeyPairGenerator
  30. * @returns {KeyPair} The generated key pair.
  31. */
  32. this.next = function() {
  33. if (policy.asymmetric.keyPair.encryption.algorithm ===
  34. Policy.options.asymmetric.keyPair.encryption.algorithm.RSA) {
  35. return generateRsaKeyPair(policy, secureRandomService);
  36. } else {
  37. throw new Error(
  38. 'Key pair generation algorithm \'' +
  39. policy.asymmetric.keyPair.encryption.algorithm +
  40. '\' is not supported.');
  41. }
  42. };
  43. /**
  44. * Generates an RSA-based key pair.
  45. *
  46. * @function generateRsaKeyPairs
  47. * @memberof KeyPairGenerator
  48. * @private
  49. * @param {Policy}
  50. * policy The cryptographic policy.
  51. * @param {SecureRandomService}
  52. * secureRandomService The secure random service.
  53. * @returns {KeyPair} The key pair.
  54. */
  55. function generateRsaKeyPair(policy, secureRandomService) {
  56. var forgeKeyPair = forge.pki.rsa.generateKeyPair(
  57. policy.asymmetric.keyPair.encryption.keyLengthBits,
  58. policy.asymmetric.keyPair.encryption.publicExponent,
  59. {prng: secureRandomService.newRandomGenerator()});
  60. var publicKey = forge.pki.publicKeyToPem(forgeKeyPair.publicKey, 64);
  61. var privateKey = forge.pki.privateKeyToPem(forgeKeyPair.privateKey, 64);
  62. return new KeyPair(publicKey, privateKey);
  63. }
  64. }