decrypter.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 Policy = require('scytl-cryptopolicy');
  11. var validator = require('./input-validator');
  12. var bitwise = require('scytl-bitwise');
  13. var codec = require('scytl-codec');
  14. var forge = require('node-forge');
  15. module.exports = AsymmetricDecrypter;
  16. /**
  17. * @class AsymmetricDecrypter
  18. * @classdesc The asymmetric decrypter API. To instantiate this object, use the
  19. * method {@link AsymmetricCryptographyService.newDecrypter}.
  20. * @hideconstructor
  21. * @param {Policy}
  22. * policy The cryptographic policy to use.
  23. */
  24. function AsymmetricDecrypter(policy) {
  25. // PRIVATE ///////////////////////////////////////////////////////////////////
  26. var algorithm_;
  27. var oaepDigester_;
  28. var oeapMaskDigester_;
  29. var kemDeriver_;
  30. var forgePrivateKey_;
  31. function initForgeCipher(algorithm) {
  32. if (algorithm.name ===
  33. Policy.options.asymmetric.cipher.algorithm.RSA_OAEP.name) {
  34. oaepDigester_ = getRsaOaepHash(algorithm.hashAlgorithm);
  35. if (algorithm.maskGenerator.name ===
  36. Policy.options.asymmetric.cipher.algorithm.RSA_OAEP.maskGenerator.MGF1
  37. .name) {
  38. oeapMaskDigester_ =
  39. getRsaOaepMaskHash(algorithm.maskGenerator.hashAlgorithm);
  40. } else {
  41. throw new Error(
  42. 'RSA-OAEP mask generation function \'' +
  43. algorithm.maskGenerator.name + '\' is not supported.');
  44. }
  45. } else if (
  46. algorithm.name ===
  47. Policy.options.asymmetric.cipher.algorithm.RSA_KEM.name) {
  48. if (algorithm.symmetricCipher !==
  49. Policy.options.asymmetric.cipher.algorithm.RSA_KEM.symmetricCipher
  50. .AES_GCM) {
  51. throw new Error(
  52. 'RSA-KEM symmetric cipher algorithm \'' +
  53. algorithm.symmetricCipher + '\' is not supported.');
  54. }
  55. kemDeriver_ = createDeriver(
  56. algorithm.keyDeriver.name, algorithm.keyDeriver.hashAlgorithm);
  57. } else {
  58. throw new Error(
  59. 'Asymmetric decryption algorithm \'' + algorithm.name +
  60. '\' is not supported.');
  61. }
  62. }
  63. // CONSTRUCTOR ///////////////////////////////////////////////////////////////
  64. algorithm_ = policy.asymmetric.cipher.algorithm;
  65. initForgeCipher(algorithm_);
  66. // PUBLIC ////////////////////////////////////////////////////////////////////
  67. /**
  68. * Initializes the asymmetric decrypter with the provided private key.
  69. *
  70. * @function init
  71. * @memberof AsymmetricDecrypter
  72. * @param {string}
  73. * privateKey The private key with which to initialize the
  74. * asymmetric decrypter, in PEM format.
  75. * @returns {AsymmetricDecrypter} A reference to this object, to facilitate
  76. * method chaining.
  77. * @throws {Error}
  78. * If the input data validation fails.
  79. */
  80. this.init = function(privateKey) {
  81. validator.checkIsNonEmptyString(
  82. privateKey,
  83. 'Private key (PEM encoded) with which to initialize asymmetric decrypter');
  84. forgePrivateKey_ = forge.pki.privateKeyFromPem(privateKey);
  85. if (typeof forgePrivateKey_.decrypt === 'undefined') {
  86. throw new Error(
  87. 'PEM encoding of private key with which to initialize asymmetric decrypter is corrupt');
  88. }
  89. return this;
  90. };
  91. /**
  92. * Asymmetrically decrypts the provided data. Before using this method, the
  93. * decrypter must have been initialized with a private key, via the method
  94. * {@link AsymmetricDecrypter.init}.
  95. *
  96. * @function decrypt
  97. * @memberof AsymmetricDecrypter
  98. * @param {Uint8Array}
  99. * encryptedData The encrypted data to decrypt.
  100. * @returns {Uint8Array} The decrypted data. <b>NOTE:</b> To retrieve data
  101. * of type <code>string</code>, apply method
  102. * <code>codec.utf8Decode</code> to result.
  103. * @throws {Error}
  104. * If the input data validation fails, the decrypter was not
  105. * initialized or the decryption process fails.
  106. */
  107. this.decrypt = function(encryptedData) {
  108. if (typeof forgePrivateKey_ === 'undefined') {
  109. throw new Error(
  110. 'Asymmetric decrypter has not been initialized with any private key');
  111. }
  112. validator.checkIsInstanceOf(
  113. encryptedData, Uint8Array, 'Uint8Array',
  114. 'Encrypted data to asymmetrically decrypt');
  115. try {
  116. var decryptedData;
  117. // Choose a decryption algorithm from the policy.
  118. switch (algorithm_.name) {
  119. case Policy.options.asymmetric.cipher.algorithm.RSA_OAEP.name:
  120. decryptedData = forgePrivateKey_.decrypt(
  121. encryptedData, algorithm_.name,
  122. {md: oaepDigester_, mgf1: {md: oeapMaskDigester_}});
  123. break;
  124. default:
  125. decryptedData = kemDecrypt(
  126. forgePrivateKey_, encryptedData, algorithm_, kemDeriver_);
  127. }
  128. return codec.binaryDecode(decryptedData);
  129. } catch (error) {
  130. throw new Error('Data could not be decrypted; ' + error);
  131. }
  132. };
  133. }
  134. // Note: at the moment, the options that are being used with the RSA_OAEP
  135. // algorithm are hardcoded (for encrypting and decrypting). This could be
  136. // improved so that these are read from the properties file. Doing this will
  137. // mean any that existing properties files (used by consumers of the
  138. // library) will become invalid (if the consumer uses RSA_OAEP) as they wont
  139. // have the mandatory new properties.
  140. function getRsaOaepHash(hashAlgorithm) {
  141. if (hashAlgorithm ===
  142. Policy.options.asymmetric.cipher.algorithm.RSA_OAEP.hashAlgorithm
  143. .SHA256) {
  144. return forge.md.sha256.create();
  145. } else {
  146. throw new Error(
  147. 'RSA-OAEP cipher hash algorithm \'' + hashAlgorithm +
  148. '\' is not supported.');
  149. }
  150. }
  151. function getRsaOaepMaskHash(hashAlgorithm) {
  152. // For interoperability purposes, the MGF1 hash function must
  153. // remain as SHA-1.
  154. if (hashAlgorithm ===
  155. Policy.options.asymmetric.cipher.algorithm.RSA_OAEP.maskGenerator.MGF1
  156. .hashAlgorithm.SHA1) {
  157. return forge.md.sha1.create();
  158. } else {
  159. throw new Error(
  160. 'RSA-OAEP cipher mask generation function hash algorithm \'' +
  161. hashAlgorithm + '\' is not supported.');
  162. }
  163. }
  164. function createDigester(hashAlgorithm) {
  165. if (hashAlgorithm ===
  166. Policy.options.asymmetric.cipher.algorithm.RSA_KEM.keyDeriver
  167. .hashAlgorithm.SHA256) {
  168. return forge.md.sha256.create();
  169. } else if (
  170. hashAlgorithm ===
  171. Policy.options.asymmetric.cipher.algorithm.RSA_KEM.keyDeriver
  172. .hashAlgorithm.SHA512_224) {
  173. return forge.md.sha512.sha224.create();
  174. } else {
  175. throw new Error(
  176. 'RSA-KEM cipher key derivation hash algorithm \'' + hashAlgorithm +
  177. '\' is not supported.');
  178. }
  179. }
  180. function createDeriver(deriverName, hashAlgorithm) {
  181. var hash = createDigester(hashAlgorithm);
  182. switch (deriverName) {
  183. case Policy.options.asymmetric.cipher.algorithm.RSA_KEM.keyDeriver.name
  184. .KDF1:
  185. return new forge.kem.kdf1(hash);
  186. case Policy.options.asymmetric.cipher.algorithm.RSA_KEM.keyDeriver.name
  187. .KDF2:
  188. return new forge.kem.kdf2(hash);
  189. case Policy.options.asymmetric.cipher.algorithm.RSA_KEM.keyDeriver.name
  190. .MGF1:
  191. return new forge.mgf.mgf1.create(hash);
  192. default:
  193. throw new Error(
  194. 'RSA-KEM cipher key derivation function \'' + deriverName +
  195. '\' is not supported.');
  196. }
  197. }
  198. /**
  199. * Decrypt some encrypted data using the 'RSA-KEM' cipher algorithm.
  200. *
  201. * @function kemDecrypt
  202. * @memberof AsymmetricDecrypter
  203. * @private
  204. * @param {Object}
  205. * privateKey The private key used for decrypting.
  206. * @param {Object}
  207. * encryptedData The encrypted data to decrypt.
  208. * @param {Object}
  209. * algorithm The cipher algorithm.
  210. * @returns {Object} The decrypted data.
  211. */
  212. function kemDecrypt(privateKey, encryptedData, algorithm, deriver) {
  213. var encryptedDataParts = parseParts(privateKey, encryptedData, algorithm);
  214. // var deriver = createDeriver(
  215. // algorithm.keyDeriver.name, algorithm.keyDeriver.hashAlgorithm);
  216. // decrypt encapsulated secret key
  217. var kem = forge.kem.rsa.create(deriver);
  218. var key = kem.decrypt(
  219. privateKey, encryptedDataParts.encapsulation,
  220. algorithm.secretKeyLengthBytes);
  221. // decrypt some bytes
  222. var decipher = forge.cipher.createDecipher(algorithm.symmetricCipher, key);
  223. decipher.start({iv: encryptedDataParts.iv, tag: encryptedDataParts.tag});
  224. decipher.update(forge.util.createBuffer(encryptedDataParts.data));
  225. var result = decipher.finish();
  226. // result will be false if there was a failure
  227. if (result) {
  228. return decipher.output.getBytes();
  229. } else {
  230. throw new Error('Data could not be KEM decrypted.');
  231. }
  232. }
  233. /**
  234. * Parses the four parts of the data that are produced by the encrypt function,
  235. * and that are received by the decrypt function.
  236. * <p>
  237. * We know the length of three of these parts, and we know the total length of
  238. * the data, therefore we can parse all four of the parts.
  239. *
  240. * @function parseParts
  241. * @memberof AsymmetricDecrypter
  242. * @private
  243. * @param {Object}
  244. * privateKey The private key used for decrypting.
  245. * @param {Object}
  246. * encryptedData The encrypted data to decrypt.
  247. * @param {Object}
  248. * algorithm The cipher algorithm. returns {Object} The object
  249. * encapsulating the parsing results.
  250. */
  251. function parseParts(privateKey, encryptedData, algorithm) {
  252. var ivLengthBytes = algorithm.ivLengthBytes;
  253. var tagLengthBytes = algorithm.tagLengthBytes;
  254. var encapsulationLengthBytes = privateKey.n.bitLength() / 8;
  255. var totalLength = encryptedData.length;
  256. var totalKnownLength =
  257. encapsulationLengthBytes + ivLengthBytes + tagLengthBytes;
  258. var encryptedDataLength = totalLength - totalKnownLength;
  259. var startIndexOfSecondPart = encapsulationLengthBytes;
  260. var startIndexOfThirdPart = startIndexOfSecondPart + ivLengthBytes;
  261. var startIndexOfFourthPart = startIndexOfThirdPart + encryptedDataLength;
  262. var encapsulation = bitwise.slice(encryptedData, 0, startIndexOfSecondPart);
  263. var iv = bitwise.slice(
  264. encryptedData, startIndexOfSecondPart, startIndexOfThirdPart);
  265. var data = bitwise.slice(
  266. encryptedData, startIndexOfThirdPart, startIndexOfFourthPart);
  267. var tag = bitwise.slice(encryptedData, startIndexOfFourthPart);
  268. return {
  269. encapsulation: codec.binaryEncode(encapsulation),
  270. iv: codec.binaryEncode(iv),
  271. data: codec.binaryEncode(data),
  272. tag: codec.binaryEncode(tag)
  273. };
  274. }