cipher.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 validator = require('./input-validator');
  11. var bitwise = require('scytl-bitwise');
  12. var codec = require('scytl-codec');
  13. var forge = require('node-forge');
  14. module.exports = SymmetricCipher;
  15. /**
  16. * @class SymmetricCipher
  17. * @classdesc The symmetric cipher API. To instantiate this object, use the
  18. * method {@link SymmetricCryptographyService.newCipher}.
  19. * @hideconstructor
  20. * @param {Policy}
  21. * policy The cryptographic policy to use.
  22. * @param {SecureRandomService}
  23. * secureRandomService The secure random service to use.
  24. */
  25. function SymmetricCipher(policy, secureRandomService) {
  26. var keyLengthBytes_ = policy.symmetric.cipher.algorithm.keyLengthBytes;
  27. var algorithm_ = policy.symmetric.cipher.algorithm.name;
  28. var tagLengthBytes_ = policy.symmetric.cipher.algorithm.tagLengthBytes;
  29. var ivLengthBytes_ = policy.symmetric.cipher.ivLengthBytes;
  30. var randomGenerator_ = secureRandomService.newRandomGenerator();
  31. var initialized_ = false;
  32. var cipher_;
  33. /**
  34. * Initializes the symmetric cipher with the provided secret key.
  35. *
  36. * @function init
  37. * @memberof SymmetricCipher
  38. * @param {Uint8Array}
  39. * key The key with which to initialize the symmetric cipher.
  40. * @returns {SymmetricCipher} A reference to this object, to facilitate
  41. * method chaining.
  42. * @throws {Error}
  43. * If the input data validation fails.
  44. */
  45. this.init = function(key) {
  46. checkInitData(key);
  47. cipher_ = forge.cipher.createCipher(algorithm_, codec.binaryEncode(key));
  48. initialized_ = true;
  49. return this;
  50. };
  51. /**
  52. * Symmetrically encrypts some data. Before using this method, the cipher
  53. * must have been initialized with a secret key, via the method
  54. * {@link SymmetricCipher.init}.
  55. *
  56. * @function encrypt
  57. * @memberof SymmetricCipher
  58. * @param {Uint8Array}
  59. * data The data to encrypt. <b>NOTE:</b> Data of type
  60. * <code>string</code> will be UTF-8 encoded.
  61. * @returns {Uint8Array} The bitwise concatenation of the initialization
  62. * vector and the encrypted data.
  63. * @throws {Error}
  64. * If the input data validation fails, the cipher was not
  65. * initialized or the encryption process fails.
  66. */
  67. this.encrypt = function(data) {
  68. if (!initialized_) {
  69. throw new Error(
  70. 'Could not encrypt; Symmetric cipher was not initialized with any secret key');
  71. }
  72. if (typeof data === 'string') {
  73. data = codec.utf8Encode(data);
  74. }
  75. validator.checkIsInstanceOf(
  76. data, Uint8Array, 'Uint8Array', 'Data to symmetrically encrypt');
  77. try {
  78. var iv = codec.binaryEncode(randomGenerator_.nextBytes(ivLengthBytes_));
  79. // Create a byte buffer for data.
  80. var dataBuffer = new forge.util.ByteBuffer(codec.binaryEncode(data));
  81. // Only for the GCM mode
  82. var gcmAuthTagByteLength = tagLengthBytes_;
  83. if (typeof gcmAuthTagBitLength !== 'undefined') {
  84. cipher_.start({iv: iv, tagLength: gcmAuthTagByteLength});
  85. } else {
  86. cipher_.start({iv: iv});
  87. }
  88. cipher_.update(dataBuffer);
  89. cipher_.finish();
  90. var encryptedData = cipher_.output.getBytes().toString();
  91. if (typeof gcmAuthTagByteLength !== 'undefined') {
  92. var gcmAuthTag = cipher_.mode.tag.getBytes();
  93. encryptedData = encryptedData + gcmAuthTag.toString();
  94. }
  95. var initVectorAndEncryptedData = iv + encryptedData;
  96. return codec.binaryDecode(initVectorAndEncryptedData);
  97. } catch (error) {
  98. throw new Error(
  99. 'Data could not be symmetrically encrypted: ' + error.message);
  100. }
  101. };
  102. /**
  103. * Symmetrically decrypts some data, using the initialization vector
  104. * provided with the encrypted data. Before using this method, the cipher
  105. * must have been initialized with a secret key, via the method
  106. * {@link SymmetricCipher.init}.
  107. *
  108. * @function decrypt
  109. * @memberof SymmetricCipher
  110. * @param {Uint8Array}
  111. * initVectorAndEncryptedData The bitwise concatenation of the
  112. * initialization vector and the encrypted data.
  113. * @returns {Uint8Array} The decrypted data. <b>NOTE:</b> To retrieve data
  114. * of type <code>string</code>, apply method
  115. * <code>codec.utf8Decode</code> to result.
  116. * @throws {Error}
  117. * If the input data validation or the decryption process fails.
  118. */
  119. this.decrypt = function(initVectorAndEncryptedData) {
  120. if (!initialized_) {
  121. throw new Error(
  122. 'Could not decrypt; Symmetric cipher was not initialized with any secret key');
  123. }
  124. validator.checkIsInstanceOf(
  125. initVectorAndEncryptedData, Uint8Array, 'Uint8Array',
  126. 'Concatenation of initialization vector and encrypted data to symmetrically decrypt');
  127. try {
  128. var initVector =
  129. bitwise.slice(initVectorAndEncryptedData, 0, ivLengthBytes_);
  130. var encryptedData = bitwise.slice(
  131. initVectorAndEncryptedData, ivLengthBytes_,
  132. initVectorAndEncryptedData.length);
  133. // Only for the GCM mode
  134. var gcmAuthTagByteLength = tagLengthBytes_;
  135. if (typeof gcmAuthTagByteLength !== 'undefined') {
  136. var offset = encryptedData.length - gcmAuthTagByteLength;
  137. var gcmAuthTag =
  138. bitwise.slice(encryptedData, offset, encryptedData.length);
  139. encryptedData = bitwise.slice(encryptedData, 0, offset);
  140. var gcmAuthTagBitLength = gcmAuthTagByteLength * 8;
  141. cipher_.start({
  142. iv: codec.binaryEncode(initVector),
  143. tagLength: gcmAuthTagBitLength,
  144. tag: codec.binaryEncode(gcmAuthTag)
  145. });
  146. } else {
  147. cipher_.start({iv: initVector});
  148. }
  149. var encryptedDataBuffer =
  150. new forge.util.ByteBuffer(codec.binaryEncode(encryptedData));
  151. cipher_.update(encryptedDataBuffer);
  152. cipher_.finish();
  153. var decryptedData =
  154. codec.binaryDecode(cipher_.output.getBytes().toString());
  155. return decryptedData;
  156. } catch (error) {
  157. throw new Error('Data could not be symmetrically decrypted; ' + error);
  158. }
  159. };
  160. function checkInitData(key) {
  161. validator.checkIsInstanceOf(
  162. key, Uint8Array, 'Uint8Array',
  163. 'Secret key with which to initialize symmetric cipher');
  164. if (key.length !== keyLengthBytes_) {
  165. throw new Error(
  166. 'Expected secret key byte length ' + keyLengthBytes_ +
  167. ' ; Found: ' + key.length);
  168. }
  169. }
  170. }