digitalenvelope.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. cryptolib.modules = cryptolib.modules || {};
  9. /**
  10. * Defines the generation and opening of digital envelopes.
  11. */
  12. cryptolib.modules.digitalenvelope = function(box) {
  13. 'use strict';
  14. box.digitalenvelope = box.digitalenvelope || {};
  15. box.digitalenvelope.factory = {};
  16. var policies = {
  17. symmetric: {
  18. secretkey: {
  19. encryption: {
  20. lengthBytes: box.policies.digitalenvelope.symmetric.secretkey
  21. .encryption.lengthBytes
  22. },
  23. mac: {
  24. lengthBytes:
  25. box.policies.digitalenvelope.symmetric.secretkey.mac.lengthBytes
  26. }
  27. }
  28. }
  29. };
  30. var exceptions;
  31. var converters;
  32. var bitOperators;
  33. var secretKeyFactory;
  34. var macDigester;
  35. var symmetricCipher;
  36. var asymmetricCipher;
  37. var f = function(box) {
  38. exceptions = box.commons.exceptions;
  39. converters = new box.commons.utils.Converters();
  40. bitOperators = new box.commons.utils.BitOperators();
  41. secretKeyFactory = new box.symmetric.secretkey.factory.SecretKeyFactory();
  42. macDigester = (new box.symmetric.mac.factory.MacFactory()).create();
  43. symmetricCipher =
  44. (new box.symmetric.cipher.factory.SymmetricCipherFactory())
  45. .getCryptoSymmetricCipher();
  46. asymmetricCipher =
  47. (new box.asymmetric.cipher.factory.AsymmetricCipherFactory())
  48. .getCryptoAsymmetricCipher();
  49. };
  50. f.policies = {
  51. symmetric: {
  52. secretkey: {
  53. encryption: {
  54. lengthBytes: box.policies.digitalenvelope.symmetric.secretkey
  55. .encryption.lengthBytes
  56. },
  57. mac: {
  58. lengthBytes:
  59. box.policies.digitalenvelope.symmetric.secretkey.mac.lengthBytes
  60. },
  61. secureRandom: {
  62. provider: box.policies.digitalenvelope.symmetric.secretkey
  63. .secureRandom.provider
  64. }
  65. },
  66. cipher: {
  67. provider: box.policies.digitalenvelope.symmetric.cipher.provider,
  68. algorithm: {
  69. AES128_GCM: {
  70. name: box.policies.digitalenvelope.symmetric.cipher.algorithm
  71. .AES128_GCM.name,
  72. keyLengthBytes: box.policies.digitalenvelope.symmetric.cipher
  73. .algorithm.AES128_GCM.keyLengthBytes,
  74. tagLengthBytes: box.policies.digitalenvelope.symmetric.cipher
  75. .algorithm.AES128_GCM.tagLengthBytes
  76. }
  77. },
  78. initializationVectorLengthBytes:
  79. box.policies.digitalenvelope.symmetric.cipher
  80. .initializationVectorLengthBytes,
  81. secureRandom: {
  82. provider: box.policies.digitalenvelope.symmetric.cipher.secureRandom
  83. .provider
  84. }
  85. },
  86. mac: {
  87. hash: box.policies.digitalenvelope.symmetric.mac.hash,
  88. provider: box.policies.digitalenvelope.symmetric.mac.provider
  89. }
  90. },
  91. asymmetric: {
  92. cipher: {
  93. algorithm: box.policies.digitalenvelope.asymmetric.cipher.algorithm,
  94. secretKeyLengthBytes:
  95. box.policies.digitalenvelope.asymmetric.cipher.secretKeyLengthBytes,
  96. ivLengthBytes:
  97. box.policies.digitalenvelope.asymmetric.cipher.ivLengthBytes,
  98. tagLengthBytes:
  99. box.policies.digitalenvelope.asymmetric.cipher.tagLengthBytes,
  100. deriver: box.policies.digitalenvelope.asymmetric.cipher.deriver,
  101. hash: box.policies.digitalenvelope.asymmetric.cipher.hash,
  102. symmetricCipher:
  103. box.policies.digitalenvelope.asymmetric.cipher.symmetricCipher,
  104. provider: box.policies.digitalenvelope.asymmetric.cipher.provider,
  105. secureRandom: {
  106. provider: box.policies.digitalenvelope.asymmetric.cipher.secureRandom
  107. .provider
  108. }
  109. }
  110. }
  111. };
  112. cryptolib('commons', 'symmetric', 'asymmetric.cipher', f);
  113. /**
  114. * Defines a factory for the creation of digital envelope generators and
  115. * openers.
  116. *
  117. * @class DigitalEnvelopeFactory
  118. * @memberof digitalenvelope
  119. */
  120. box.digitalenvelope.factory.DigitalEnvelopeFactory = function() {
  121. };
  122. box.digitalenvelope.factory.DigitalEnvelopeFactory.prototype = {
  123. /**
  124. * Obtains a new digital envelope generator.
  125. *
  126. * @function getDigitalEnvelopeGenerator
  127. * @return {DigitalEnvelopeGenerator} the digital envelope generator.
  128. */
  129. getDigitalEnvelopeGenerator: function() {
  130. try {
  131. return new box.digitalenvelope.DigitalEnvelopeGenerator();
  132. } catch (error) {
  133. throw new exceptions.CryptoLibException(
  134. 'Could not obtain a digital envelope generator.', error);
  135. }
  136. },
  137. /**
  138. * Obtains new a digital envelope opener.
  139. *
  140. * @function getDigitalEnvelopeOpener
  141. * @return {DigitalEnvelopeOpener} the digital envelope opener.
  142. */
  143. getDigitalEnvelopeOpener: function() {
  144. try {
  145. return new box.digitalenvelope.DigitalEnvelopeOpener();
  146. } catch (error) {
  147. throw new exceptions.CryptoLibException(
  148. 'Could not obtain a digital envelope opener.', error);
  149. }
  150. }
  151. };
  152. /**
  153. * Defines a digital envelope generator.
  154. *
  155. * @class DigitalEnvelopeGenerator
  156. * @memberof digitalenvelope
  157. */
  158. box.digitalenvelope.DigitalEnvelopeGenerator = function() {
  159. };
  160. box.digitalenvelope.DigitalEnvelopeGenerator.prototype = {
  161. /**
  162. * Generates a digital envelope for some data. The envelope can be
  163. * generated with one or more public keys, each of whose corresponding
  164. * private key can be used to open the envelope.
  165. *
  166. * @function generate
  167. * @param dataBase64
  168. * {string} the data to store in the digital envelope, as a
  169. * string in Base64 encoded format.
  170. * @param publicKeysPem
  171. * {string[]} a list of one or more public keys used to
  172. * generate the digital envelope, as an array of strings in
  173. * PEM format.
  174. * @return {DigitalEnvelope} the generated digital envelope.
  175. */
  176. generate: function(dataBase64, publicKeysPem) {
  177. try {
  178. validateGeneratorInput(dataBase64, publicKeysPem);
  179. // Generate encryption secret key and use it to symmetrically encrypt
  180. // data.
  181. var secretKeyForEncryptionBase64 =
  182. secretKeyFactory.getCryptoSecretKeyGeneratorForEncryption()
  183. .generate();
  184. var encryptedDataBase64 =
  185. symmetricCipher.encrypt(secretKeyForEncryptionBase64, dataBase64);
  186. // Generate MAC secret key and use it to generate MAC of symmetrically
  187. // Base64 encryption of encrypted data.
  188. var secretKeyForMacBase64 =
  189. secretKeyFactory.getCryptoSecretKeyGeneratorForMac().generate();
  190. var encryptedDataBase64Base64 =
  191. converters.base64Encode(encryptedDataBase64);
  192. var macBase64 = macDigester.generate(
  193. secretKeyForMacBase64, [encryptedDataBase64Base64]);
  194. // Construct bit-wise concatenation of encryption and MAC secret keys.
  195. var secretKeyForEncryption =
  196. converters.base64Decode(secretKeyForEncryptionBase64);
  197. var secretKeyForMac = converters.base64Decode(secretKeyForMacBase64);
  198. var secretKeyConcatenation =
  199. secretKeyForEncryption.toString() + secretKeyForMac.toString();
  200. var secretKeyConcatenationBase64 =
  201. converters.base64Encode(secretKeyConcatenation);
  202. // Generate list of asymmetric encryptions of the secret key
  203. // concatenation, each encryption created using a different one of the
  204. // public keys provided as input for the digital envelope generation.
  205. var secretKeyEncryptions = [];
  206. for (var i = 0; i < publicKeysPem.length; i++) {
  207. var publicKeyPem = publicKeysPem[i];
  208. var encryptedSecretKeyConcatentionBase64 = asymmetricCipher.encrypt(
  209. publicKeyPem, secretKeyConcatenationBase64);
  210. secretKeyEncryptions.push(new SecretKeyEncryption(
  211. encryptedSecretKeyConcatentionBase64, publicKeyPem));
  212. }
  213. return new DigitalEnvelope(
  214. encryptedDataBase64, macBase64, secretKeyEncryptions);
  215. } catch (error) {
  216. throw new exceptions.CryptoLibException(
  217. 'Digital envelope could not be generated.', error);
  218. }
  219. }
  220. };
  221. /**
  222. * Defines a digital envelope opener.
  223. *
  224. * @class DigitalEnvelopeOpener
  225. * @memberof digitalenvelope
  226. */
  227. box.digitalenvelope.DigitalEnvelopeOpener = function() {
  228. this._getEncryptedSecretKeyConcatenation = function(
  229. secretKeyEncryptions, privateKeyPem) {
  230. // Extract modulus and public exponent from private key.
  231. var privateKey = box.forge.pki.privateKeyFromPem(privateKeyPem);
  232. var modulus = privateKey.n;
  233. var publicExponent = privateKey.e;
  234. for (var i = 0; i < secretKeyEncryptions.length; i++) {
  235. var publicKeyPem = secretKeyEncryptions[i].getPublicKey();
  236. var publicKey = box.forge.pki.publicKeyFromPem(publicKeyPem);
  237. if (publicKey.n.equals(modulus) && publicKey.e.equals(publicExponent)) {
  238. return secretKeyEncryptions[i].getEncryptedSecretKeyConcatenation();
  239. }
  240. }
  241. throw new exceptions.CryptoLibException(
  242. 'Could not find an asymmetric encryption of the secret key concatenation that could be decrypted using the private key provided.');
  243. };
  244. };
  245. box.digitalenvelope.DigitalEnvelopeOpener.prototype = {
  246. /**
  247. * Opens a digital envelope and retrieves its data. The envelope can be
  248. * opened with any private key corresponding to a public key that was
  249. * used to generate the envelope.
  250. *
  251. * @function open
  252. * @param digitalEnvelope
  253. * {DigitalEnvelope} the digital envelope to open.
  254. * @param privateKeyPem
  255. * {string} the private key used to open the digital
  256. * envelope, as a string in PEM format.
  257. * @return {string} the data stored in the digital envelope, as a string
  258. * in Base64 encoded format.
  259. */
  260. open: function(digitalEnvelope, privateKeyPem) {
  261. try {
  262. validateOpenerInput(digitalEnvelope, privateKeyPem);
  263. // Retrieve data from digital envelope.
  264. var encryptedDataBase64 = digitalEnvelope.getEncryptedData();
  265. var macBase64 = digitalEnvelope.getMac();
  266. var secretKeyEncryptions = digitalEnvelope.getSecretKeyEncryptions();
  267. // Retrieve asymmetric encryption of bit-wise concatenation of
  268. // encryption and MAC secret keys that can be decrypted with private
  269. // key provided as input.
  270. var encryptedSecretKeyConcatenationBase64 =
  271. this._getEncryptedSecretKeyConcatenation(
  272. secretKeyEncryptions, privateKeyPem);
  273. // Asymmetrically decrypt bit-wise concatenation of encryption and MAC
  274. // secret keys.
  275. var secretKeyConcatenationBase64 = asymmetricCipher.decrypt(
  276. privateKeyPem, encryptedSecretKeyConcatenationBase64);
  277. var secretKeyConcatenation =
  278. converters.base64Decode(secretKeyConcatenationBase64);
  279. // Extract secret keys from bit-wise concatenation.
  280. var secretKeyForEncryptionLength =
  281. policies.symmetric.secretkey.encryption.lengthBytes;
  282. var secretKeyForMacLength =
  283. policies.symmetric.secretkey.mac.lengthBytes;
  284. var secretKeyForEncryption = bitOperators.extract(
  285. secretKeyConcatenation, 0, secretKeyForEncryptionLength);
  286. var secretKeyForEncryptionBase64 =
  287. converters.base64Encode(secretKeyForEncryption);
  288. var secretKeyForMac = bitOperators.extract(
  289. secretKeyConcatenation, secretKeyForEncryptionLength,
  290. secretKeyForEncryptionLength + secretKeyForMacLength);
  291. var secretKeyForMacBase64 = converters.base64Encode(secretKeyForMac);
  292. // Check integrity of digital envelope.
  293. var encryptedDataBase64Base64 =
  294. converters.base64Encode(encryptedDataBase64);
  295. if (!macDigester.verify(
  296. macBase64, secretKeyForMacBase64,
  297. [encryptedDataBase64Base64])) {
  298. throw new exceptions.CryptoLibException(
  299. 'Integrity of digital envelope could not be verified.');
  300. }
  301. return symmetricCipher.decrypt(
  302. secretKeyForEncryptionBase64, encryptedDataBase64);
  303. } catch (error) {
  304. throw new exceptions.CryptoLibException(
  305. 'Digital envelope could not be opened.', error);
  306. }
  307. }
  308. };
  309. /**
  310. * Container class for a digital envelope.
  311. *
  312. * @class DigitalEnvelope
  313. * @param encryptedDataBase64
  314. * {string} the symmetrically encrypted data, as a string in
  315. * Base64 encoded format.
  316. * @param macBase64
  317. * {string} the MAC of the symmetrically encrypted data, as a
  318. * string in Base64 encoded format.
  319. * @param secretKeyEncryptions
  320. * {SecretKeyEncryption[]} the list of asymmetric encryptions of
  321. * the secret key concatenation, each encryption having been
  322. * created using a different one of the public keys provided as
  323. * input to the digital envelope generator.
  324. * @memberof digitalenvelope
  325. */
  326. function DigitalEnvelope(
  327. encryptedDataBase64, macBase64, secretKeyEncryptions) {
  328. this.encryptedDataBase64 = encryptedDataBase64;
  329. this.macBase64 = macBase64;
  330. this.secretKeyEncryptions = secretKeyEncryptions;
  331. var _encryptedSecretKeyConcatsBase64 = [];
  332. var _publicKeysPem = [];
  333. for (var i = 0; i < secretKeyEncryptions.length; i++) {
  334. _encryptedSecretKeyConcatsBase64[i] =
  335. secretKeyEncryptions[i].getEncryptedSecretKeyConcatenation();
  336. _publicKeysPem[i] = secretKeyEncryptions[i].getPublicKey();
  337. }
  338. this._getEncryptedSecretKeyConcatsBase64 = function() {
  339. return _encryptedSecretKeyConcatsBase64;
  340. };
  341. this._getPublicKeysPem = function() {
  342. return _publicKeysPem;
  343. };
  344. }
  345. DigitalEnvelope.prototype = {
  346. /**
  347. * @function getEncryptedData
  348. * @return {string} the symmetrically encrypted data, as a string in
  349. * Base64 encoded format.
  350. */
  351. getEncryptedData: function() {
  352. return this.encryptedDataBase64;
  353. },
  354. /**
  355. * @function getMac
  356. * @return {string} the MAC of the symmetrically encrypted data, as a
  357. * string in Base64 encoded format.
  358. */
  359. getMac: function() {
  360. return this.macBase64;
  361. },
  362. /**
  363. * @function getSecretKeyEncryptions
  364. * @return {SecretKeyEncryption[]} the list of asymmetric encryptions of
  365. * the secret key concatenation.
  366. */
  367. getSecretKeyEncryptions: function() {
  368. return this.secretKeyEncryptions;
  369. },
  370. /**
  371. * Generates a string representation of the digital envelope.
  372. * <p>
  373. * Note: in order to permit interoperability between libraries, this
  374. * representation should match the equivalent representation in Java.
  375. *
  376. * @function stringify
  377. * @return {string} the string representation of the digital envelope.
  378. */
  379. stringify: function() {
  380. return JSON.stringify({
  381. digitalEnvelope: {
  382. encryptedDataBase64: this.encryptedDataBase64,
  383. macBase64: this.macBase64,
  384. encryptedSecretKeyConcatsBase64:
  385. this._getEncryptedSecretKeyConcatsBase64(),
  386. publicKeysPem: this._getPublicKeysPem()
  387. }
  388. });
  389. }
  390. };
  391. /**
  392. * Container class for the asymmetric encryption of the bit-wise
  393. * concatenation of the secret key used to symmetrically encrypt the data of
  394. * a digital envelope and the secret key used to generate an MAC for
  395. * checking the integrity of the symmetric encryption. The public key used
  396. * to perform the asymmetric encryption of the secret key concatenation is
  397. * also included.
  398. *
  399. * @class SecretKeyEncryption
  400. * @param encryptedSecretKeyConcatBase64
  401. * {string} the asymmetric encryption of the secret key
  402. * concatenation, using the public key provided as input, as a
  403. * string in Base64 encoded format.
  404. * @param publicKeyPem
  405. * {string} the public key, of type
  406. * {@link java.security.PublicKey}, used to asymmetrically
  407. * encrypt the secret key concatenation.
  408. * @memberof digitalenvelope
  409. */
  410. function SecretKeyEncryption(encryptedSecretKeyConcatBase64, publicKeyPem) {
  411. /**
  412. * @function getEncryptedSecretKeyConcatenationBase64
  413. * @return {string} the asymmetrically encrypted secret key
  414. * concatenation, as a string in Base64 encoded format.
  415. */
  416. var getEncryptedSecretKeyConcatenation = function() {
  417. return encryptedSecretKeyConcatBase64;
  418. };
  419. /**
  420. * @function getPublicKey
  421. * @return {string} the public key used to asymmetrically encrypt the
  422. * secret key concatenation, as a string in PEM format.
  423. */
  424. var getPublicKey = function() {
  425. return publicKeyPem;
  426. };
  427. return {
  428. getEncryptedSecretKeyConcatenation: getEncryptedSecretKeyConcatenation,
  429. getPublicKey: getPublicKey
  430. };
  431. }
  432. /**
  433. * Deserializes a digital envelope.
  434. *
  435. * @function deserialize
  436. * @param serializedDigitalEnvelope
  437. * {string} the serialized digital envelope.
  438. * @return {DigitalEnvelope} the digital envelope after deserialization.
  439. * @memberof digitalenvelope
  440. */
  441. box.digitalenvelope.deserialize = function(serializedDigitalEnvelope) {
  442. validateDeserializerInput(serializedDigitalEnvelope);
  443. var digitalEnvelopeJson =
  444. JSON.parse(serializedDigitalEnvelope).digitalEnvelope;
  445. var encryptedDataBase64 = digitalEnvelopeJson.encryptedDataBase64;
  446. var macBase64 = digitalEnvelopeJson.macBase64;
  447. var encryptedSecretKeyConcatsBase64 =
  448. digitalEnvelopeJson.encryptedSecretKeyConcatsBase64;
  449. var publicKeysPem = digitalEnvelopeJson.publicKeysPem;
  450. var secretKeyEncryptions = [];
  451. for (var i = 0; i < encryptedSecretKeyConcatsBase64.length; i++) {
  452. secretKeyEncryptions.push(new SecretKeyEncryption(
  453. encryptedSecretKeyConcatsBase64[i], publicKeysPem[i]));
  454. }
  455. return new DigitalEnvelope(
  456. encryptedDataBase64, macBase64, secretKeyEncryptions);
  457. };
  458. function validateGeneratorInput(dataBase64, publicKeysPem) {
  459. if (typeof dataBase64 === 'undefined') {
  460. throw new exceptions.CryptoLibException(
  461. 'Data provided to digital envelope generator is undefined.');
  462. }
  463. if (converters.base64Decode(dataBase64) === '') {
  464. throw new exceptions.CryptoLibException(
  465. 'Data provided to digital envelope generator is empty.');
  466. }
  467. if (typeof dataBase64 !== 'string') {
  468. throw new exceptions.CryptoLibException(
  469. 'Base64 encoded data provided to digital envelope generator is not a String.');
  470. }
  471. if (typeof publicKeysPem === 'undefined') {
  472. throw new exceptions.CryptoLibException(
  473. 'Public key array provided to digital envelope generator is undefined.');
  474. }
  475. if (!(publicKeysPem instanceof Array)) {
  476. throw new exceptions.CryptoLibException(
  477. 'Public key array provided to digital envelope generator is not of type Array.');
  478. }
  479. if (publicKeysPem.length === 0) {
  480. throw new exceptions.CryptoLibException(
  481. 'Public key array provided to digital envelope generator is empty.');
  482. }
  483. }
  484. function validateOpenerInput(digitalEnvelope, privateKeyPem) {
  485. if (typeof digitalEnvelope === 'undefined') {
  486. throw new exceptions.CryptoLibException(
  487. 'Digital envelope provided to digital envelope opener is undefined.');
  488. }
  489. if (!(digitalEnvelope instanceof Object)) {
  490. throw new exceptions.CryptoLibException(
  491. 'Digital envelope provided to digital envelope generator is not of type Object.');
  492. }
  493. if (typeof privateKeyPem === 'undefined') {
  494. throw new exceptions.CryptoLibException(
  495. 'Private key provided to digital envelope opener is undefined.');
  496. }
  497. if (typeof privateKeyPem !== 'string') {
  498. throw new exceptions.CryptoLibException(
  499. 'Private key PEM provided to digital envelope opener is not of type String.');
  500. }
  501. }
  502. function validateDeserializerInput(serializedDigitalEnvelope) {
  503. if (typeof serializedDigitalEnvelope === 'undefined') {
  504. throw new exceptions.CryptoLibException(
  505. 'Serialized object provided to digital envelope deserializer is undefined.');
  506. }
  507. if (typeof serializedDigitalEnvelope !== 'string') {
  508. throw new exceptions.CryptoLibException(
  509. 'Serialized object provided to digital envelope deserializer is not of type String.');
  510. }
  511. if (serializedDigitalEnvelope.length === 0) {
  512. throw new exceptions.CryptoLibException(
  513. 'Serialized object provided to digital envelope deserializer is empty.');
  514. }
  515. }
  516. };