PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/core/codecs/aes-crypto-stream.js

https://github.com/gildas-lormeau/zip.js
JavaScript | 278 lines | 230 code | 19 blank | 29 comment | 42 complexity | 604d38ba59c59c15bcccff92d0263a56 MD5 | raw file
  1. /*
  2. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. 1. Redistributions of source code must retain the above copyright notice,
  6. this list of conditions and the following disclaimer.
  7. 2. Redistributions in binary form must reproduce the above copyright
  8. notice, this list of conditions and the following disclaimer in
  9. the documentation and/or other materials provided with the distribution.
  10. 3. The names of the authors may not be used to endorse or promote products
  11. derived from this software without specific prior written permission.
  12. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  13. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  14. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  15. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  16. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  17. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  18. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  19. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  20. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  21. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. /* global crypto, TransformStream */
  24. // deno-lint-ignore-file no-this-alias
  25. import encodeText from "./../util/encode-text.js";
  26. import { cipher, codec, misc, mode, random } from "./sjcl.js";
  27. const ERR_INVALID_PASSWORD = "Invalid pasword";
  28. const BLOCK_LENGTH = 16;
  29. const RAW_FORMAT = "raw";
  30. const PBKDF2_ALGORITHM = { name: "PBKDF2" };
  31. const HASH_ALGORITHM = { name: "HMAC" };
  32. const HASH_FUNCTION = "SHA-1";
  33. const BASE_KEY_ALGORITHM = Object.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
  34. const DERIVED_BITS_ALGORITHM = Object.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
  35. const DERIVED_BITS_USAGE = ["deriveBits"];
  36. const SALT_LENGTH = [8, 12, 16];
  37. const KEY_LENGTH = [16, 24, 32];
  38. const SIGNATURE_LENGTH = 10;
  39. const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
  40. const UNDEFINED_TYPE = "undefined";
  41. const FUNCTION_TYPE = "function";
  42. const CRYPTO_API_SUPPORTED = typeof crypto != UNDEFINED_TYPE;
  43. const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof crypto.subtle != UNDEFINED_TYPE;
  44. const GET_RANDOM_VALUES_SUPPORTED = CRYPTO_API_SUPPORTED && typeof crypto.getRandomValues == FUNCTION_TYPE;
  45. const IMPORT_KEY_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.importKey == FUNCTION_TYPE;
  46. const DERIVE_BITS_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.deriveBits == FUNCTION_TYPE;
  47. const codecBytes = codec.bytes;
  48. const Aes = cipher.aes;
  49. const CtrGladman = mode.ctrGladman;
  50. const HmacSha1 = misc.hmacSha1;
  51. class AESDecryptionStream extends TransformStream {
  52. constructor(password, signed, strength) {
  53. let stream;
  54. super({
  55. start() {
  56. Object.assign(this, {
  57. ready: new Promise(resolve => this.resolveReady = resolve),
  58. password,
  59. signed,
  60. strength: strength - 1,
  61. pending: new Uint8Array(0)
  62. });
  63. },
  64. async transform(chunk, controller) {
  65. if (chunk && chunk.length) {
  66. const aesCrypto = this;
  67. if (aesCrypto.password) {
  68. const password = aesCrypto.password;
  69. aesCrypto.password = null;
  70. const preamble = subarray(chunk, 0, SALT_LENGTH[aesCrypto.strength] + 2);
  71. await createDecryptionKeys(aesCrypto, preamble, password);
  72. aesCrypto.ctr = new CtrGladman(new Aes(aesCrypto.keys.key), Array.from(COUNTER_DEFAULT_VALUE));
  73. aesCrypto.hmac = new HmacSha1(aesCrypto.keys.authentication);
  74. chunk = subarray(chunk, SALT_LENGTH[aesCrypto.strength] + 2);
  75. aesCrypto.resolveReady();
  76. } else {
  77. await aesCrypto.ready;
  78. }
  79. const output = new Uint8Array(chunk.length - SIGNATURE_LENGTH - ((chunk.length - SIGNATURE_LENGTH) % BLOCK_LENGTH));
  80. controller.enqueue(append(aesCrypto, chunk, output, 0, SIGNATURE_LENGTH, true));
  81. }
  82. },
  83. async flush(controller) {
  84. const aesCrypto = this;
  85. await aesCrypto.ready;
  86. const pending = aesCrypto.pending;
  87. const chunkToDecrypt = subarray(pending, 0, pending.length - SIGNATURE_LENGTH);
  88. const originalSignature = subarray(pending, pending.length - SIGNATURE_LENGTH);
  89. let decryptedChunkArray = new Uint8Array(0);
  90. if (chunkToDecrypt.length) {
  91. const encryptedChunk = toBits(codecBytes, chunkToDecrypt);
  92. aesCrypto.hmac.update(encryptedChunk);
  93. const decryptedChunk = aesCrypto.ctr.update(encryptedChunk);
  94. decryptedChunkArray = fromBits(codecBytes, decryptedChunk);
  95. }
  96. stream.valid = true;
  97. if (aesCrypto.signed) {
  98. const signature = subarray(fromBits(codecBytes, aesCrypto.hmac.digest()), 0, SIGNATURE_LENGTH);
  99. for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) {
  100. if (signature[indexSignature] != originalSignature[indexSignature]) {
  101. stream.valid = false;
  102. }
  103. }
  104. }
  105. controller.enqueue(decryptedChunkArray);
  106. }
  107. });
  108. stream = this;
  109. }
  110. }
  111. class AESEncryptionStream extends TransformStream {
  112. constructor(password, strength) {
  113. let stream;
  114. super({
  115. start() {
  116. Object.assign(this, {
  117. ready: new Promise(resolve => this.resolveReady = resolve),
  118. password,
  119. strength: strength - 1,
  120. pending: new Uint8Array(0)
  121. });
  122. },
  123. async transform(chunk, controller) {
  124. if (chunk && chunk.length) {
  125. const aesCrypto = this;
  126. let preamble = new Uint8Array(0);
  127. if (aesCrypto.password) {
  128. const password = aesCrypto.password;
  129. aesCrypto.password = null;
  130. preamble = await createEncryptionKeys(aesCrypto, password);
  131. aesCrypto.ctr = new CtrGladman(new Aes(aesCrypto.keys.key), Array.from(COUNTER_DEFAULT_VALUE));
  132. aesCrypto.hmac = new HmacSha1(aesCrypto.keys.authentication);
  133. aesCrypto.resolveReady();
  134. } else {
  135. await aesCrypto.ready;
  136. }
  137. const output = new Uint8Array(preamble.length + chunk.length - (chunk.length % BLOCK_LENGTH));
  138. output.set(preamble, 0);
  139. controller.enqueue(append(aesCrypto, chunk, output, preamble.length, 0));
  140. }
  141. },
  142. async flush(controller) {
  143. const aesCrypto = this;
  144. await aesCrypto.ready;
  145. let encryptedChunkArray = new Uint8Array(0);
  146. if (aesCrypto.pending.length) {
  147. const encryptedChunk = aesCrypto.ctr.update(toBits(codecBytes, aesCrypto.pending));
  148. aesCrypto.hmac.update(encryptedChunk);
  149. encryptedChunkArray = fromBits(codecBytes, encryptedChunk);
  150. }
  151. stream.signature = fromBits(codecBytes, aesCrypto.hmac.digest()).slice(0, SIGNATURE_LENGTH);
  152. controller.enqueue(concat(encryptedChunkArray, stream.signature));
  153. }
  154. });
  155. stream = this;
  156. }
  157. }
  158. export {
  159. AESDecryptionStream,
  160. AESEncryptionStream,
  161. ERR_INVALID_PASSWORD
  162. };
  163. function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) {
  164. const inputLength = input.length - paddingEnd;
  165. if (aesCrypto.pending.length) {
  166. input = concat(aesCrypto.pending, input);
  167. output = expand(output, inputLength - (inputLength % BLOCK_LENGTH));
  168. }
  169. let offset;
  170. for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) {
  171. const inputChunk = toBits(codecBytes, subarray(input, offset, offset + BLOCK_LENGTH));
  172. if (verifySignature) {
  173. aesCrypto.hmac.update(inputChunk);
  174. }
  175. const outputChunk = aesCrypto.ctr.update(inputChunk);
  176. if (!verifySignature) {
  177. aesCrypto.hmac.update(outputChunk);
  178. }
  179. output.set(fromBits(codecBytes, outputChunk), offset + paddingStart);
  180. }
  181. aesCrypto.pending = subarray(input, offset);
  182. return output;
  183. }
  184. async function createDecryptionKeys(decrypt, preambleArray, password) {
  185. await createKeys(decrypt, password, subarray(preambleArray, 0, SALT_LENGTH[decrypt.strength]));
  186. const passwordVerification = subarray(preambleArray, SALT_LENGTH[decrypt.strength]);
  187. const passwordVerificationKey = decrypt.keys.passwordVerification;
  188. if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
  189. throw new Error(ERR_INVALID_PASSWORD);
  190. }
  191. }
  192. async function createEncryptionKeys(encrypt, password) {
  193. const salt = getRandomValues(new Uint8Array(SALT_LENGTH[encrypt.strength]));
  194. await createKeys(encrypt, password, salt);
  195. return concat(salt, encrypt.keys.passwordVerification);
  196. }
  197. async function createKeys(target, password, salt) {
  198. const encodedPassword = encodeText(password);
  199. const basekey = await importKey(RAW_FORMAT, encodedPassword, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE);
  200. const derivedBits = await deriveBits(Object.assign({ salt }, DERIVED_BITS_ALGORITHM), basekey, 8 * ((KEY_LENGTH[target.strength] * 2) + 2));
  201. const compositeKey = new Uint8Array(derivedBits);
  202. target.keys = {
  203. key: toBits(codecBytes, subarray(compositeKey, 0, KEY_LENGTH[target.strength])),
  204. authentication: toBits(codecBytes, subarray(compositeKey, KEY_LENGTH[target.strength], KEY_LENGTH[target.strength] * 2)),
  205. passwordVerification: subarray(compositeKey, KEY_LENGTH[target.strength] * 2)
  206. };
  207. }
  208. function getRandomValues(array) {
  209. if (GET_RANDOM_VALUES_SUPPORTED) {
  210. return crypto.getRandomValues(array);
  211. } else {
  212. return random.getRandomValues(array);
  213. }
  214. }
  215. function importKey(format, password, algorithm, extractable, keyUsages) {
  216. if (IMPORT_KEY_SUPPORTED) {
  217. return crypto.subtle.importKey(format, password, algorithm, extractable, keyUsages);
  218. } else {
  219. return misc.importKey(password);
  220. }
  221. }
  222. async function deriveBits(algorithm, baseKey, length) {
  223. if (DERIVE_BITS_SUPPORTED) {
  224. return await crypto.subtle.deriveBits(algorithm, baseKey, length);
  225. } else {
  226. return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  227. }
  228. }
  229. function concat(leftArray, rightArray) {
  230. let array = leftArray;
  231. if (leftArray.length + rightArray.length) {
  232. array = new Uint8Array(leftArray.length + rightArray.length);
  233. array.set(leftArray, 0);
  234. array.set(rightArray, leftArray.length);
  235. }
  236. return array;
  237. }
  238. function expand(inputArray, length) {
  239. if (length && length > inputArray.length) {
  240. const array = inputArray;
  241. inputArray = new Uint8Array(length);
  242. inputArray.set(array, 0);
  243. }
  244. return inputArray;
  245. }
  246. function subarray(array, begin, end) {
  247. return array.subarray(begin, end);
  248. }
  249. function fromBits(codecBytes, chunk) {
  250. return codecBytes.fromBits(chunk);
  251. }
  252. function toBits(codecBytes, chunk) {
  253. return codecBytes.toBits(chunk);
  254. }