node-opcua-crypto 1.11.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.fossa.yml +18 -18
  2. package/.github/FUNDING.yml +12 -12
  3. package/.github/workflows/main.yml +32 -32
  4. package/.prettierrc.js +6 -6
  5. package/LICENSE +23 -22
  6. package/README.md +14 -14
  7. package/dist/source/asn1.d.ts +73 -73
  8. package/dist/source/asn1.js +359 -359
  9. package/dist/source/buffer_utils.d.ts +6 -6
  10. package/dist/source/buffer_utils.js +21 -21
  11. package/dist/source/certificate_matches_private_key.d.ts +2 -0
  12. package/dist/source/certificate_matches_private_key.js +22 -0
  13. package/dist/source/certificate_matches_private_key.js.map +1 -0
  14. package/dist/source/common.d.ts +12 -12
  15. package/dist/source/common.js +2 -2
  16. package/dist/source/crypto_explore_certificate.d.ts +107 -107
  17. package/dist/source/crypto_explore_certificate.js +601 -600
  18. package/dist/source/crypto_explore_certificate.js.map +1 -1
  19. package/dist/source/crypto_utils.d.ts +80 -78
  20. package/dist/source/crypto_utils.js +312 -280
  21. package/dist/source/crypto_utils.js.map +1 -1
  22. package/dist/source/derived_keys.d.ts +72 -72
  23. package/dist/source/derived_keys.js +248 -248
  24. package/dist/source/explore_certificate.d.ts +30 -30
  25. package/dist/source/explore_certificate.js +43 -43
  26. package/dist/source/explore_certificate_revocation_list.d.ts +28 -28
  27. package/dist/source/explore_certificate_revocation_list.js +69 -69
  28. package/dist/source/explore_certificate_signing_request.d.ts +13 -13
  29. package/dist/source/explore_certificate_signing_request.js +44 -44
  30. package/dist/source/explore_private_key.d.ts +29 -29
  31. package/dist/source/explore_private_key.js +96 -96
  32. package/dist/source/explore_private_key.js.map +1 -1
  33. package/dist/source/index.d.ts +13 -13
  34. package/dist/source/index.js +29 -29
  35. package/dist/source/oid_map.d.ts +7 -7
  36. package/dist/source/oid_map.js +303 -303
  37. package/dist/source/public_private_match.d.ts +3 -3
  38. package/dist/source/public_private_match.js +37 -16
  39. package/dist/source/public_private_match.js.map +1 -1
  40. package/dist/source/verify_certificate_signature.d.ts +10 -10
  41. package/dist/source/verify_certificate_signature.js +101 -101
  42. package/dist/source_nodejs/index.d.ts +3 -3
  43. package/dist/source_nodejs/index.js +19 -19
  44. package/dist/source_nodejs/read.d.ts +29 -29
  45. package/dist/source_nodejs/read.js +94 -94
  46. package/dist/source_nodejs/read.js.map +1 -1
  47. package/dist/source_nodejs/read_certificate_revocation_list.d.ts +2 -2
  48. package/dist/source_nodejs/read_certificate_revocation_list.js +27 -27
  49. package/dist/source_nodejs/read_certificate_signing_request.d.ts +3 -3
  50. package/dist/source_nodejs/read_certificate_signing_request.js +27 -27
  51. package/index.d.ts +2 -2
  52. package/index.js +4 -4
  53. package/index_web.js +3 -3
  54. package/package.json +12 -12
  55. package/source/asn1.ts +404 -404
  56. package/source/buffer_utils.ts +18 -18
  57. package/source/common.ts +13 -13
  58. package/source/crypto_explore_certificate.ts +764 -763
  59. package/source/crypto_utils.ts +359 -321
  60. package/source/derived_keys.ts +287 -287
  61. package/source/explore_certificate.ts +66 -66
  62. package/source/explore_certificate_revocation_list.ts +122 -122
  63. package/source/explore_certificate_signing_request.ts +58 -58
  64. package/source/explore_private_key.ts +121 -121
  65. package/source/index.ts +13 -13
  66. package/source/oid_map.ts +310 -310
  67. package/source/public_private_match.ts +41 -18
  68. package/source/verify_certificate_signature.ts +105 -105
  69. package/source_nodejs/index.ts +2 -2
  70. package/source_nodejs/read.ts +95 -95
  71. package/source_nodejs/read_certificate_revocation_list.ts +14 -14
  72. package/source_nodejs/read_certificate_signing_request.ts +17 -17
  73. package/test_certificate.ts +34 -34
  74. package/tsconfig.json +18 -18
  75. package/tslint.json +34 -34
  76. package/dist/asn1.d.ts +0 -69
  77. package/dist/asn1.js +0 -349
  78. package/dist/asn1.js.map +0 -1
  79. package/dist/buffer_utils.d.ts +0 -6
  80. package/dist/buffer_utils.js +0 -22
  81. package/dist/buffer_utils.js.map +0 -1
  82. package/dist/common.d.ts +0 -11
  83. package/dist/common.js +0 -3
  84. package/dist/common.js.map +0 -1
  85. package/dist/crypto_explore_certificate.d.ts +0 -95
  86. package/dist/crypto_explore_certificate.js +0 -547
  87. package/dist/crypto_explore_certificate.js.map +0 -1
  88. package/dist/crypto_utils.d.ts +0 -106
  89. package/dist/crypto_utils.js +0 -370
  90. package/dist/crypto_utils.js.map +0 -1
  91. package/dist/derived_keys.d.ts +0 -72
  92. package/dist/derived_keys.js +0 -247
  93. package/dist/derived_keys.js.map +0 -1
  94. package/dist/explore_certificate.d.ts +0 -30
  95. package/dist/explore_certificate.js +0 -44
  96. package/dist/explore_certificate.js.map +0 -1
  97. package/dist/explore_certificate_revocation_list.d.ts +0 -30
  98. package/dist/explore_certificate_revocation_list.js +0 -67
  99. package/dist/explore_certificate_revocation_list.js.map +0 -1
  100. package/dist/index.d.ts +0 -10
  101. package/dist/index.js +0 -23
  102. package/dist/index.js.map +0 -1
  103. package/dist/oid_map.d.ts +0 -7
  104. package/dist/oid_map.js +0 -262
  105. package/dist/oid_map.js.map +0 -1
  106. package/dist/verify_cerficate_signature.d.ts +0 -10
  107. package/dist/verify_cerficate_signature.js +0 -102
  108. package/dist/verify_cerficate_signature.js.map +0 -1
@@ -1,287 +1,287 @@
1
- /**
2
- * @module node_opcua_crypto
3
- */
4
- import * as crypto from "crypto";
5
-
6
- import { createFastUninitializedBuffer } from "./buffer_utils";
7
- import { Nonce } from "./common";
8
- import { verifyMessageChunkSignature, VerifyMessageChunkSignatureOptions } from "./crypto_utils";
9
- import { exploreCertificateInfo } from "./explore_certificate";
10
- import * as assert from "assert";
11
-
12
- function HMAC_HASH(sha1or256: "SHA1" | "SHA256", secret: Buffer, message: Buffer) {
13
- return crypto.createHmac(sha1or256, secret).update(message).digest();
14
- }
15
-
16
- function plus(buf1: Buffer, buf2: Buffer): Buffer {
17
- return Buffer.concat([buf1, buf2]);
18
- }
19
-
20
- // OPC-UA Spec 1.02 part 6 - 6.7.5 Deriving Keys page 42
21
- // Once the SecureChannel is established the Messages are signed and encrypted with keys derived
22
- // from the Nonces exchanged in t he OpenSecureChannel call. These keys are derived by passing the
23
- // Nonces to a pseudo - random function which produces a sequence of bytes from a set of inputs. A
24
- // pseudo- random function is represented by the following function declaration:
25
- // Byte[] PRF(
26
- // Byte[] secret,
27
- // Byte[] seed,
28
- // Int32 length,
29
- // Int32 offset
30
- // )
31
- // Where length is the number of bytes to return and offset is a number of bytes from the beginning of
32
- // the sequence.
33
- // The lengths of the keys that need to be generated depend on the SecurityPolicy used for the
34
- // channel. The following information is specified by the SecurityPolicy:
35
- // a) SigningKeyLength (from the DerivedSignatureKeyLength);
36
- // b) EncryptingKeyLength (implied by the SymmetricEncryptionAlgorithm);
37
- // c) EncryptingBlockSize (implied by the SymmetricEncryptionAlgorithm).
38
- // The parameters passed to the pseudo random function are specified in Table 36.
39
- // Table 36 - Cryptography Key Generation Parameters
40
- //
41
- // Key Secret Seed Length Offset
42
- // ClientSigningKey ServerNonce ClientNonce SigningKeyLength 0
43
- // ClientEncryptingKey ServerNonce ClientNonce EncryptingKeyLength SigningKeyLength
44
- // ClientInitializationVector ServerNonce ClientNonce EncryptingBlockSize SigningKeyLength+ EncryptingKeyLength
45
- // ServerSigningKey ClientNonce ServerNonce SigningKeyLength 0
46
- // ServerEncryptingKey ClientNonce ServerNonce EncryptingKeyLength SigningKeyLength
47
- // ServerInitializationVector ClientNonce ServerNonce EncryptingBlockSize SigningKeyLength+ EncryptingKeyLength
48
- //
49
- // The Client keys are used to secure Messages sent by the Client. The Server keys are used to
50
- // secure Messages sent by the Server.
51
- // The SSL/TLS specification defines a pseudo random function called P_HASH which is used for this purpose.
52
- //
53
- // The P_HASH algorithm is defined as follows:
54
- //
55
- // P_HASH(secret, seed) = HMAC_HASH(secret, A(1) + seed) +
56
- // HMAC_HASH(secret, A(2) + seed) +
57
- // HMAC_HASH(secret, A(3) + seed) + ...
58
- // Where A(n) is defined as:
59
- // A(0) = seed
60
- // A(n) = HMAC_HASH(secret, A(n-1))
61
- // + indicates that the results are appended to previous results.
62
- // Where HASH is a hash function such as SHA1 or SHA256. The hash function to use depends on the SecurityPolicyUri.
63
- //
64
- //
65
- // see also http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/ws-secureconversation-1.3-os.html
66
- // http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
67
- export function makePseudoRandomBuffer(secret: Nonce, seed: Nonce, minLength: number, sha1or256: "SHA1" | "SHA256"): Buffer {
68
- assert(seed instanceof Buffer);
69
- assert(sha1or256 === "SHA1" || sha1or256 === "SHA256");
70
-
71
- const a = [];
72
- a[0] = seed;
73
- let index = 1;
74
- let p_hash = createFastUninitializedBuffer(0);
75
- while (p_hash.length <= minLength) {
76
- /* eslint new-cap:0 */
77
- a[index] = HMAC_HASH(sha1or256, secret, a[index - 1]);
78
- p_hash = plus(p_hash, HMAC_HASH(sha1or256, secret, plus(a[index], seed)));
79
- index += 1;
80
- }
81
- return p_hash.slice(0, minLength);
82
- }
83
-
84
- export interface ComputeDerivedKeysOptions {
85
- signatureLength: number;
86
- signingKeyLength: number;
87
- encryptingKeyLength: number;
88
-
89
- encryptingBlockSize: number;
90
- algorithm: string;
91
- sha1or256?: "SHA1" | "SHA256";
92
- }
93
-
94
- export interface DerivedKeys extends ComputeDerivedKeysOptions {
95
- signatureLength: number;
96
- signingKeyLength: number;
97
- encryptingKeyLength: number;
98
-
99
- encryptingBlockSize: number;
100
- algorithm: string;
101
- sha1or256: "SHA1" | "SHA256";
102
-
103
- signingKey: Buffer;
104
- encryptingKey: Buffer;
105
- initializationVector: Buffer;
106
- }
107
-
108
- export function computeDerivedKeys(secret: Nonce, seed: Nonce, options: ComputeDerivedKeysOptions): DerivedKeys {
109
- assert(Number.isFinite(options.signatureLength));
110
- assert(Number.isFinite(options.encryptingKeyLength));
111
- assert(Number.isFinite(options.encryptingBlockSize));
112
- assert(typeof options.algorithm === "string");
113
- options.sha1or256 = options.sha1or256 || "SHA1";
114
- assert(typeof options.sha1or256 === "string");
115
-
116
- const offset1 = options.signingKeyLength;
117
- const offset2 = offset1 + options.encryptingKeyLength;
118
- const minLength = offset2 + options.encryptingBlockSize;
119
-
120
- const buf = makePseudoRandomBuffer(secret, seed, minLength, options.sha1or256);
121
-
122
- // +---------------+---------------------+-----------------------+
123
- // + signingKey + encryptingKey + initializationVector +
124
- // +---------------+---------------------+-----------------------+
125
- return {
126
- signatureLength: options.signatureLength,
127
- signingKeyLength: options.signingKeyLength,
128
- encryptingKeyLength: options.encryptingKeyLength,
129
-
130
- encryptingBlockSize: options.encryptingBlockSize,
131
- algorithm: options.algorithm,
132
- sha1or256: options.sha1or256,
133
-
134
- signingKey: buf.slice(0, offset1),
135
- encryptingKey: buf.slice(offset1, offset2),
136
- initializationVector: buf.slice(offset2, minLength),
137
- };
138
- }
139
-
140
- /**
141
- * @method reduceLength
142
- * @param buffer
143
- * @param byteToRemove
144
- * @return buffer
145
- */
146
- export function reduceLength(buffer: Buffer, byteToRemove: number): Buffer {
147
- return buffer.slice(0, buffer.length - byteToRemove);
148
- }
149
-
150
- /**
151
- * @method removePadding
152
- * @param buffer
153
- * @return buffer with padding removed
154
- */
155
- export function removePadding(buffer: Buffer): Buffer {
156
- const nbPaddingBytes = buffer.readUInt8(buffer.length - 1) + 1;
157
- return reduceLength(buffer, nbPaddingBytes);
158
- }
159
-
160
- export type VerifyChunkSignatureOptions = VerifyMessageChunkSignatureOptions;
161
-
162
- /**
163
- * @method verifyChunkSignature
164
- *
165
- * const signer = {
166
- * signatureLength : 128,
167
- * algorithm : "RSA-SHA256",
168
- * public_key: "qsdqsdqsd"
169
- * };
170
- *
171
- * @param chunk The message chunk to verify.
172
- * @param options
173
- * @param options.signatureLength
174
- * @param options.algorithm the algorithm.
175
- * @param options.publicKey
176
- * @return {*}
177
- */
178
- export function verifyChunkSignature(chunk: Buffer, options: VerifyChunkSignatureOptions): boolean {
179
- assert(chunk instanceof Buffer);
180
- let signatureLength = options.signatureLength || 0;
181
- if (signatureLength === 0) {
182
- // let's get the signatureLength by checking the size
183
- // of the certificate's public key
184
- const cert = exploreCertificateInfo(options.publicKey);
185
- signatureLength = cert.publicKeyLength || 0; // 1024 bits = 128Bytes or 2048=256Bytes
186
- }
187
- const block_to_verify = chunk.slice(0, chunk.length - signatureLength);
188
- const signature = chunk.slice(chunk.length - signatureLength);
189
- return verifyMessageChunkSignature(block_to_verify, signature, options);
190
- }
191
-
192
- // /**
193
- // * extract the public key from a certificate - using the pem module
194
- // *
195
- // * @method extractPublicKeyFromCertificate_WithPem
196
- // * @async
197
- // * @param certificate
198
- // * @param callback {Function}
199
- // * @param callback.err
200
- // * @param callback.publicKey as pem
201
- // */
202
- // exports.extractPublicKeyFromCertificate_WithPem = function (certificate, callback) {
203
- //
204
- // const err1 = new Error();
205
- // const cert_pem = crypto_utils.toPem(certificate, "CERTIFICATE");
206
- // require("pem").getPublicKey(cert_pem, function (err, data) {
207
- // if (err) {
208
- // console.log(err1.stack);
209
- // console.log(" CANNOT EXTRAT PUBLIC KEY from Certificate".red, certificate);
210
- // return callback(err);
211
- // }
212
- // callback(err, data.publicKey);
213
- // });
214
- // };
215
- //
216
-
217
- export function computePaddingFooter(buffer: Buffer, derivedKeys: DerivedKeys): Buffer {
218
- assert(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
219
- const paddingSize = derivedKeys.encryptingBlockSize - ((buffer.length + 1) % derivedKeys.encryptingBlockSize);
220
- const padding = createFastUninitializedBuffer(paddingSize + 1);
221
- padding.fill(paddingSize);
222
- return padding;
223
- }
224
-
225
- function derivedKeys_algorithm(derivedKeys: DerivedKeys) {
226
- assert(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
227
- const algorithm = derivedKeys.algorithm || "aes-128-cbc";
228
- assert(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
229
- return algorithm;
230
- }
231
-
232
- export function encryptBufferWithDerivedKeys(buffer: Buffer, derivedKeys: DerivedKeys): Buffer {
233
- const algorithm = derivedKeys_algorithm(derivedKeys);
234
- const key = derivedKeys.encryptingKey;
235
- const initVector = derivedKeys.initializationVector;
236
- const cypher = crypto.createCipheriv(algorithm, key, initVector);
237
-
238
- cypher.setAutoPadding(false);
239
- const encrypted_chunks = [];
240
- encrypted_chunks.push(cypher.update(buffer));
241
- encrypted_chunks.push(cypher.final());
242
- return Buffer.concat(encrypted_chunks);
243
- }
244
-
245
- export function decryptBufferWithDerivedKeys(buffer: Buffer, derivedKeys: DerivedKeys): Buffer {
246
- const algorithm = derivedKeys_algorithm(derivedKeys);
247
- const key = derivedKeys.encryptingKey;
248
- const initVector = derivedKeys.initializationVector;
249
- const cypher = crypto.createDecipheriv(algorithm, key, initVector);
250
-
251
- cypher.setAutoPadding(false);
252
-
253
- const decrypted_chunks = [];
254
- decrypted_chunks.push(cypher.update(buffer));
255
- decrypted_chunks.push(cypher.final());
256
-
257
- return Buffer.concat(decrypted_chunks);
258
- }
259
-
260
- /**
261
- * @method makeMessageChunkSignatureWithDerivedKeys
262
- * @param message
263
- * @param derivedKeys
264
- * @return
265
- */
266
- export function makeMessageChunkSignatureWithDerivedKeys(message: Buffer, derivedKeys: DerivedKeys): Buffer {
267
- assert(message instanceof Buffer);
268
- assert(derivedKeys.signingKey instanceof Buffer);
269
- assert(typeof derivedKeys.sha1or256 === "string");
270
- assert(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
271
- const signature = crypto.createHmac(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
272
- assert(signature.length === derivedKeys.signatureLength);
273
- return signature;
274
- }
275
-
276
- /**
277
- * @method verifyChunkSignatureWithDerivedKeys
278
- * @param chunk
279
- * @param derivedKeys
280
- * @return
281
- */
282
- export function verifyChunkSignatureWithDerivedKeys(chunk: Buffer, derivedKeys: DerivedKeys): boolean {
283
- const message = chunk.slice(0, chunk.length - derivedKeys.signatureLength);
284
- const signature = chunk.slice(chunk.length - derivedKeys.signatureLength);
285
- const verif = makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys);
286
- return verif.toString("hex") === signature.toString("hex");
287
- }
1
+ /**
2
+ * @module node_opcua_crypto
3
+ */
4
+ import * as crypto from "crypto";
5
+
6
+ import { createFastUninitializedBuffer } from "./buffer_utils";
7
+ import { Nonce } from "./common";
8
+ import { verifyMessageChunkSignature, VerifyMessageChunkSignatureOptions } from "./crypto_utils";
9
+ import { exploreCertificateInfo } from "./explore_certificate";
10
+ import * as assert from "assert";
11
+
12
+ function HMAC_HASH(sha1or256: "SHA1" | "SHA256", secret: Buffer, message: Buffer) {
13
+ return crypto.createHmac(sha1or256, secret).update(message).digest();
14
+ }
15
+
16
+ function plus(buf1: Buffer, buf2: Buffer): Buffer {
17
+ return Buffer.concat([buf1, buf2]);
18
+ }
19
+
20
+ // OPC-UA Spec 1.02 part 6 - 6.7.5 Deriving Keys page 42
21
+ // Once the SecureChannel is established the Messages are signed and encrypted with keys derived
22
+ // from the Nonces exchanged in t he OpenSecureChannel call. These keys are derived by passing the
23
+ // Nonces to a pseudo - random function which produces a sequence of bytes from a set of inputs. A
24
+ // pseudo- random function is represented by the following function declaration:
25
+ // Byte[] PRF(
26
+ // Byte[] secret,
27
+ // Byte[] seed,
28
+ // Int32 length,
29
+ // Int32 offset
30
+ // )
31
+ // Where length is the number of bytes to return and offset is a number of bytes from the beginning of
32
+ // the sequence.
33
+ // The lengths of the keys that need to be generated depend on the SecurityPolicy used for the
34
+ // channel. The following information is specified by the SecurityPolicy:
35
+ // a) SigningKeyLength (from the DerivedSignatureKeyLength);
36
+ // b) EncryptingKeyLength (implied by the SymmetricEncryptionAlgorithm);
37
+ // c) EncryptingBlockSize (implied by the SymmetricEncryptionAlgorithm).
38
+ // The parameters passed to the pseudo random function are specified in Table 36.
39
+ // Table 36 - Cryptography Key Generation Parameters
40
+ //
41
+ // Key Secret Seed Length Offset
42
+ // ClientSigningKey ServerNonce ClientNonce SigningKeyLength 0
43
+ // ClientEncryptingKey ServerNonce ClientNonce EncryptingKeyLength SigningKeyLength
44
+ // ClientInitializationVector ServerNonce ClientNonce EncryptingBlockSize SigningKeyLength+ EncryptingKeyLength
45
+ // ServerSigningKey ClientNonce ServerNonce SigningKeyLength 0
46
+ // ServerEncryptingKey ClientNonce ServerNonce EncryptingKeyLength SigningKeyLength
47
+ // ServerInitializationVector ClientNonce ServerNonce EncryptingBlockSize SigningKeyLength+ EncryptingKeyLength
48
+ //
49
+ // The Client keys are used to secure Messages sent by the Client. The Server keys are used to
50
+ // secure Messages sent by the Server.
51
+ // The SSL/TLS specification defines a pseudo random function called P_HASH which is used for this purpose.
52
+ //
53
+ // The P_HASH algorithm is defined as follows:
54
+ //
55
+ // P_HASH(secret, seed) = HMAC_HASH(secret, A(1) + seed) +
56
+ // HMAC_HASH(secret, A(2) + seed) +
57
+ // HMAC_HASH(secret, A(3) + seed) + ...
58
+ // Where A(n) is defined as:
59
+ // A(0) = seed
60
+ // A(n) = HMAC_HASH(secret, A(n-1))
61
+ // + indicates that the results are appended to previous results.
62
+ // Where HASH is a hash function such as SHA1 or SHA256. The hash function to use depends on the SecurityPolicyUri.
63
+ //
64
+ //
65
+ // see also http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/ws-secureconversation-1.3-os.html
66
+ // http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
67
+ export function makePseudoRandomBuffer(secret: Nonce, seed: Nonce, minLength: number, sha1or256: "SHA1" | "SHA256"): Buffer {
68
+ assert(seed instanceof Buffer);
69
+ assert(sha1or256 === "SHA1" || sha1or256 === "SHA256");
70
+
71
+ const a = [];
72
+ a[0] = seed;
73
+ let index = 1;
74
+ let p_hash = createFastUninitializedBuffer(0);
75
+ while (p_hash.length <= minLength) {
76
+ /* eslint new-cap:0 */
77
+ a[index] = HMAC_HASH(sha1or256, secret, a[index - 1]);
78
+ p_hash = plus(p_hash, HMAC_HASH(sha1or256, secret, plus(a[index], seed)));
79
+ index += 1;
80
+ }
81
+ return p_hash.slice(0, minLength);
82
+ }
83
+
84
+ export interface ComputeDerivedKeysOptions {
85
+ signatureLength: number;
86
+ signingKeyLength: number;
87
+ encryptingKeyLength: number;
88
+
89
+ encryptingBlockSize: number;
90
+ algorithm: string;
91
+ sha1or256?: "SHA1" | "SHA256";
92
+ }
93
+
94
+ export interface DerivedKeys extends ComputeDerivedKeysOptions {
95
+ signatureLength: number;
96
+ signingKeyLength: number;
97
+ encryptingKeyLength: number;
98
+
99
+ encryptingBlockSize: number;
100
+ algorithm: string;
101
+ sha1or256: "SHA1" | "SHA256";
102
+
103
+ signingKey: Buffer;
104
+ encryptingKey: Buffer;
105
+ initializationVector: Buffer;
106
+ }
107
+
108
+ export function computeDerivedKeys(secret: Nonce, seed: Nonce, options: ComputeDerivedKeysOptions): DerivedKeys {
109
+ assert(Number.isFinite(options.signatureLength));
110
+ assert(Number.isFinite(options.encryptingKeyLength));
111
+ assert(Number.isFinite(options.encryptingBlockSize));
112
+ assert(typeof options.algorithm === "string");
113
+ options.sha1or256 = options.sha1or256 || "SHA1";
114
+ assert(typeof options.sha1or256 === "string");
115
+
116
+ const offset1 = options.signingKeyLength;
117
+ const offset2 = offset1 + options.encryptingKeyLength;
118
+ const minLength = offset2 + options.encryptingBlockSize;
119
+
120
+ const buf = makePseudoRandomBuffer(secret, seed, minLength, options.sha1or256);
121
+
122
+ // +---------------+---------------------+-----------------------+
123
+ // + signingKey + encryptingKey + initializationVector +
124
+ // +---------------+---------------------+-----------------------+
125
+ return {
126
+ signatureLength: options.signatureLength,
127
+ signingKeyLength: options.signingKeyLength,
128
+ encryptingKeyLength: options.encryptingKeyLength,
129
+
130
+ encryptingBlockSize: options.encryptingBlockSize,
131
+ algorithm: options.algorithm,
132
+ sha1or256: options.sha1or256,
133
+
134
+ signingKey: buf.slice(0, offset1),
135
+ encryptingKey: buf.slice(offset1, offset2),
136
+ initializationVector: buf.slice(offset2, minLength),
137
+ };
138
+ }
139
+
140
+ /**
141
+ * @method reduceLength
142
+ * @param buffer
143
+ * @param byteToRemove
144
+ * @return buffer
145
+ */
146
+ export function reduceLength(buffer: Buffer, byteToRemove: number): Buffer {
147
+ return buffer.slice(0, buffer.length - byteToRemove);
148
+ }
149
+
150
+ /**
151
+ * @method removePadding
152
+ * @param buffer
153
+ * @return buffer with padding removed
154
+ */
155
+ export function removePadding(buffer: Buffer): Buffer {
156
+ const nbPaddingBytes = buffer.readUInt8(buffer.length - 1) + 1;
157
+ return reduceLength(buffer, nbPaddingBytes);
158
+ }
159
+
160
+ export type VerifyChunkSignatureOptions = VerifyMessageChunkSignatureOptions;
161
+
162
+ /**
163
+ * @method verifyChunkSignature
164
+ *
165
+ * const signer = {
166
+ * signatureLength : 128,
167
+ * algorithm : "RSA-SHA256",
168
+ * public_key: "qsdqsdqsd"
169
+ * };
170
+ *
171
+ * @param chunk The message chunk to verify.
172
+ * @param options
173
+ * @param options.signatureLength
174
+ * @param options.algorithm the algorithm.
175
+ * @param options.publicKey
176
+ * @return {*}
177
+ */
178
+ export function verifyChunkSignature(chunk: Buffer, options: VerifyChunkSignatureOptions): boolean {
179
+ assert(chunk instanceof Buffer);
180
+ let signatureLength = options.signatureLength || 0;
181
+ if (signatureLength === 0) {
182
+ // let's get the signatureLength by checking the size
183
+ // of the certificate's public key
184
+ const cert = exploreCertificateInfo(options.publicKey);
185
+ signatureLength = cert.publicKeyLength || 0; // 1024 bits = 128Bytes or 2048=256Bytes
186
+ }
187
+ const block_to_verify = chunk.slice(0, chunk.length - signatureLength);
188
+ const signature = chunk.slice(chunk.length - signatureLength);
189
+ return verifyMessageChunkSignature(block_to_verify, signature, options);
190
+ }
191
+
192
+ // /**
193
+ // * extract the public key from a certificate - using the pem module
194
+ // *
195
+ // * @method extractPublicKeyFromCertificate_WithPem
196
+ // * @async
197
+ // * @param certificate
198
+ // * @param callback {Function}
199
+ // * @param callback.err
200
+ // * @param callback.publicKey as pem
201
+ // */
202
+ // exports.extractPublicKeyFromCertificate_WithPem = function (certificate, callback) {
203
+ //
204
+ // const err1 = new Error();
205
+ // const cert_pem = crypto_utils.toPem(certificate, "CERTIFICATE");
206
+ // require("pem").getPublicKey(cert_pem, function (err, data) {
207
+ // if (err) {
208
+ // console.log(err1.stack);
209
+ // console.log(" CANNOT EXTRAT PUBLIC KEY from Certificate".red, certificate);
210
+ // return callback(err);
211
+ // }
212
+ // callback(err, data.publicKey);
213
+ // });
214
+ // };
215
+ //
216
+
217
+ export function computePaddingFooter(buffer: Buffer, derivedKeys: DerivedKeys): Buffer {
218
+ assert(Object.prototype.hasOwnProperty.call(derivedKeys, "encryptingBlockSize"));
219
+ const paddingSize = derivedKeys.encryptingBlockSize - ((buffer.length + 1) % derivedKeys.encryptingBlockSize);
220
+ const padding = createFastUninitializedBuffer(paddingSize + 1);
221
+ padding.fill(paddingSize);
222
+ return padding;
223
+ }
224
+
225
+ function derivedKeys_algorithm(derivedKeys: DerivedKeys) {
226
+ assert(Object.prototype.hasOwnProperty.call(derivedKeys, "algorithm"));
227
+ const algorithm = derivedKeys.algorithm || "aes-128-cbc";
228
+ assert(algorithm === "aes-128-cbc" || algorithm === "aes-256-cbc");
229
+ return algorithm;
230
+ }
231
+
232
+ export function encryptBufferWithDerivedKeys(buffer: Buffer, derivedKeys: DerivedKeys): Buffer {
233
+ const algorithm = derivedKeys_algorithm(derivedKeys);
234
+ const key = derivedKeys.encryptingKey;
235
+ const initVector = derivedKeys.initializationVector;
236
+ const cypher = crypto.createCipheriv(algorithm, key, initVector);
237
+
238
+ cypher.setAutoPadding(false);
239
+ const encrypted_chunks = [];
240
+ encrypted_chunks.push(cypher.update(buffer));
241
+ encrypted_chunks.push(cypher.final());
242
+ return Buffer.concat(encrypted_chunks);
243
+ }
244
+
245
+ export function decryptBufferWithDerivedKeys(buffer: Buffer, derivedKeys: DerivedKeys): Buffer {
246
+ const algorithm = derivedKeys_algorithm(derivedKeys);
247
+ const key = derivedKeys.encryptingKey;
248
+ const initVector = derivedKeys.initializationVector;
249
+ const cypher = crypto.createDecipheriv(algorithm, key, initVector);
250
+
251
+ cypher.setAutoPadding(false);
252
+
253
+ const decrypted_chunks = [];
254
+ decrypted_chunks.push(cypher.update(buffer));
255
+ decrypted_chunks.push(cypher.final());
256
+
257
+ return Buffer.concat(decrypted_chunks);
258
+ }
259
+
260
+ /**
261
+ * @method makeMessageChunkSignatureWithDerivedKeys
262
+ * @param message
263
+ * @param derivedKeys
264
+ * @return
265
+ */
266
+ export function makeMessageChunkSignatureWithDerivedKeys(message: Buffer, derivedKeys: DerivedKeys): Buffer {
267
+ assert(message instanceof Buffer);
268
+ assert(derivedKeys.signingKey instanceof Buffer);
269
+ assert(typeof derivedKeys.sha1or256 === "string");
270
+ assert(derivedKeys.sha1or256 === "SHA1" || derivedKeys.sha1or256 === "SHA256");
271
+ const signature = crypto.createHmac(derivedKeys.sha1or256, derivedKeys.signingKey).update(message).digest();
272
+ assert(signature.length === derivedKeys.signatureLength);
273
+ return signature;
274
+ }
275
+
276
+ /**
277
+ * @method verifyChunkSignatureWithDerivedKeys
278
+ * @param chunk
279
+ * @param derivedKeys
280
+ * @return
281
+ */
282
+ export function verifyChunkSignatureWithDerivedKeys(chunk: Buffer, derivedKeys: DerivedKeys): boolean {
283
+ const message = chunk.slice(0, chunk.length - derivedKeys.signatureLength);
284
+ const signature = chunk.slice(chunk.length - derivedKeys.signatureLength);
285
+ const verif = makeMessageChunkSignatureWithDerivedKeys(message, derivedKeys);
286
+ return verif.toString("hex") === signature.toString("hex");
287
+ }