node-opcua-crypto 2.1.2 → 3.0.0-beta.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 (117) hide show
  1. package/.fossa.yml +18 -18
  2. package/.github/FUNDING.yml +12 -12
  3. package/.github/workflows/main.yml +109 -106
  4. package/.prettierrc.js +6 -6
  5. package/LICENSE +23 -23
  6. package/README.md +14 -14
  7. package/_tmp_certificate.pem +20 -0
  8. package/_tmp_csr.pem +17 -0
  9. package/_tmp_privatekey.der +0 -0
  10. package/_tmp_privatekey.pem +28 -0
  11. package/dist/source/asn1.d.ts +73 -73
  12. package/dist/source/asn1.js +359 -359
  13. package/dist/source/asn1.js.map +1 -1
  14. package/dist/source/buffer_utils.d.ts +5 -6
  15. package/dist/source/buffer_utils.js +21 -21
  16. package/dist/source/common.d.ts +20 -14
  17. package/dist/source/common.js +10 -2
  18. package/dist/source/common.js.map +1 -1
  19. package/dist/source/create_key_pair.d.ts +42 -0
  20. package/dist/source/create_key_pair.js +136 -0
  21. package/dist/source/create_key_pair.js.map +1 -0
  22. package/dist/source/crypto_explore_certificate.d.ts +107 -107
  23. package/dist/source/crypto_explore_certificate.js +601 -601
  24. package/dist/source/crypto_utils.d.ts +76 -76
  25. package/dist/source/crypto_utils.js +329 -329
  26. package/dist/source/derived_keys.d.ts +72 -72
  27. package/dist/source/derived_keys.js +248 -248
  28. package/dist/source/explore_certificate.d.ts +30 -30
  29. package/dist/source/explore_certificate.js +43 -43
  30. package/dist/source/explore_certificate_revocation_list.d.ts +28 -28
  31. package/dist/source/explore_certificate_revocation_list.js +69 -69
  32. package/dist/source/explore_certificate_signing_request.d.ts +13 -13
  33. package/dist/source/explore_certificate_signing_request.js +44 -44
  34. package/dist/source/explore_private_key.d.ts +29 -29
  35. package/dist/source/explore_private_key.js +95 -97
  36. package/dist/source/explore_private_key.js.map +1 -1
  37. package/dist/source/index.d.ts +17 -13
  38. package/dist/source/index.js +33 -29
  39. package/dist/source/index.js.map +1 -1
  40. package/dist/source/oid_map.d.ts +7 -7
  41. package/dist/source/oid_map.js +303 -303
  42. package/dist/source/public_private_match.d.ts +3 -3
  43. package/dist/source/public_private_match.js +36 -36
  44. package/dist/source/subject.d.ts +27 -0
  45. package/dist/source/subject.js +125 -0
  46. package/dist/source/subject.js.map +1 -0
  47. package/dist/source/verify_certificate_signature.d.ts +10 -10
  48. package/dist/source/verify_certificate_signature.js +101 -101
  49. package/dist/source/x509/_build_public_key.d.ts +1 -0
  50. package/dist/source/x509/_build_public_key.js +36 -0
  51. package/dist/source/x509/_build_public_key.js.map +1 -0
  52. package/dist/source/x509/_crypto.d.ts +3 -0
  53. package/dist/source/x509/_crypto.js +9 -0
  54. package/dist/source/x509/_crypto.js.map +1 -0
  55. package/dist/source/x509/_fix.d.ts +2 -0
  56. package/dist/source/x509/_fix.js +74 -0
  57. package/dist/source/x509/_fix.js.map +1 -0
  58. package/dist/source/x509/_get_attributes.d.ts +8 -0
  59. package/dist/source/x509/_get_attributes.js +56 -0
  60. package/dist/source/x509/_get_attributes.js.map +1 -0
  61. package/dist/source/x509/_internals.d.ts +0 -0
  62. package/dist/source/x509/_internals.js +2 -0
  63. package/dist/source/x509/_internals.js.map +1 -0
  64. package/dist/source/x509/create_certificate_signing_request.d.ts +18 -0
  65. package/dist/source/x509/create_certificate_signing_request.js +53 -0
  66. package/dist/source/x509/create_certificate_signing_request.js.map +1 -0
  67. package/dist/source/x509/create_key_pair.d.ts +28 -0
  68. package/dist/source/x509/create_key_pair.js +62 -0
  69. package/dist/source/x509/create_key_pair.js.map +1 -0
  70. package/dist/source/x509/create_self_signed_certificate.d.ts +17 -0
  71. package/dist/source/x509/create_self_signed_certificate.js +71 -0
  72. package/dist/source/x509/create_self_signed_certificate.js.map +1 -0
  73. package/dist/source_nodejs/generate_private_key_filename.d.ts +1 -0
  74. package/dist/source_nodejs/generate_private_key_filename.js +25 -0
  75. package/dist/source_nodejs/generate_private_key_filename.js.map +1 -0
  76. package/dist/source_nodejs/index.d.ts +4 -3
  77. package/dist/source_nodejs/index.js +20 -19
  78. package/dist/source_nodejs/index.js.map +1 -1
  79. package/dist/source_nodejs/read.d.ts +23 -23
  80. package/dist/source_nodejs/read.js +106 -106
  81. package/dist/source_nodejs/read_certificate_revocation_list.d.ts +2 -2
  82. package/dist/source_nodejs/read_certificate_revocation_list.js +27 -27
  83. package/dist/source_nodejs/read_certificate_signing_request.d.ts +3 -3
  84. package/dist/source_nodejs/read_certificate_signing_request.js +27 -27
  85. package/index.d.ts +2 -2
  86. package/index.js +4 -4
  87. package/index_web.js +3 -3
  88. package/package.json +15 -9
  89. package/source/asn1.ts +404 -404
  90. package/source/buffer_utils.ts +18 -18
  91. package/source/common.ts +7 -0
  92. package/source/crypto_explore_certificate.ts +764 -764
  93. package/source/derived_keys.ts +287 -287
  94. package/source/explore_certificate.ts +66 -66
  95. package/source/explore_certificate_revocation_list.ts +122 -122
  96. package/source/explore_certificate_signing_request.ts +58 -58
  97. package/source/explore_private_key.ts +1 -2
  98. package/source/index.ts +17 -13
  99. package/source/oid_map.ts +310 -310
  100. package/source/subject.ts +144 -0
  101. package/source/verify_certificate_signature.ts +105 -105
  102. package/source/x509/_build_public_key.ts +25 -0
  103. package/source/x509/_crypto.ts +5 -0
  104. package/source/x509/_get_attributes.ts +60 -0
  105. package/source/x509/create_certificate_signing_request.ts +64 -0
  106. package/source/x509/create_key_pair.ts +70 -0
  107. package/source/x509/create_self_signed_certificate.ts +91 -0
  108. package/source_nodejs/generate_private_key_filename.ts +10 -0
  109. package/source_nodejs/index.ts +4 -3
  110. package/source_nodejs/read_certificate_revocation_list.ts +14 -14
  111. package/source_nodejs/read_certificate_signing_request.ts +17 -17
  112. package/test_certificate.ts +34 -34
  113. package/tsconfig.json +19 -18
  114. package/tslint.json +34 -34
  115. package/dist/source/certificate_matches_private_key.d.ts +0 -2
  116. package/dist/source/certificate_matches_private_key.js +0 -22
  117. package/dist/source/certificate_matches_private_key.js.map +0 -1
@@ -1,330 +1,330 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractPublicKeyFromCertificate = exports.extractPublicKeyFromCertificateSync = exports.rsaLengthRsaPublicKey = exports.rsaLengthPublicKey = exports.rsaLengthPrivateKey = exports.coercePrivateKeyPem = exports.coercePrivateKey = exports.coerceRsaPublicKeyPem = exports.coercePublicKeyPem = exports.coerceCertificatePem = exports.privateDecrypt_long = exports.publicEncrypt_long = exports.privateDecrypt = exports.publicEncrypt = exports.privateDecrypt_native = exports.publicEncrypt_native = exports.PaddingAlgorithm = exports.RSA_PKCS1_PADDING = exports.RSA_PKCS1_OAEP_PADDING = exports.makeSHA1Thumbprint = exports.verifyMessageChunkSignature = exports.makeMessageChunkSignature = exports.hexDump = exports.toPem = exports.convertPEMtoDER = exports.identifyPemType = void 0;
4
- // tslint:disabled:no-var-requires
5
- /**
6
- * @module node_opcua_crypto
7
- */
8
- const constants = require("constants");
9
- const crypto = require("crypto");
10
- const buffer_utils_1 = require("./buffer_utils");
11
- const crypto_explore_certificate_1 = require("./crypto_explore_certificate");
12
- const assert = require("assert");
13
- const hexy_1 = require("hexy");
14
- const jsrsasign = require("jsrsasign");
15
- const PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
16
- const PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
17
- // Copyright 2012 The Obvious Corporation.
18
- // identifyPemType
19
- /*=
20
- * Extract and identify the PEM file type represented in the given
21
- * buffer. Returns the extracted type string or undefined if the
22
- * buffer doesn't seem to be any sort of PEM format file.
23
- */
24
- function identifyPemType(rawKey) {
25
- if (rawKey instanceof Buffer) {
26
- rawKey = rawKey.toString("utf8");
27
- }
28
- const match = PEM_TYPE_REGEX.exec(rawKey);
29
- return !match ? undefined : match[2];
30
- }
31
- exports.identifyPemType = identifyPemType;
32
- function convertPEMtoDER(raw_key) {
33
- let match;
34
- let pemType;
35
- let base64str;
36
- const parts = [];
37
- PEM_REGEX.lastIndex = 0;
38
- // tslint:disable-next-line:no-conditional-assignment
39
- while ((match = PEM_REGEX.exec(raw_key)) !== null) {
40
- pemType = match[2];
41
- // pemType shall be "RSA PRIVATE KEY" , "PUBLIC KEY", "CERTIFICATE", "X509 CRL"
42
- base64str = match[3];
43
- base64str = base64str.replace(/\r?\n/g, "");
44
- parts.push(Buffer.from(base64str, "base64"));
45
- }
46
- return (0, crypto_explore_certificate_1.combine_der)(parts);
47
- }
48
- exports.convertPEMtoDER = convertPEMtoDER;
49
- /**
50
- * @method toPem
51
- * @param raw_key
52
- * @param pem
53
- * @return
54
- */
55
- function toPem(raw_key, pem) {
56
- assert(raw_key, "expecting a key");
57
- assert(typeof pem === "string");
58
- if (raw_key instanceof crypto.KeyObject) {
59
- if (pem === "RSA PRIVATE KEY") {
60
- return raw_key.export({ format: "pem", type: "pkcs1" }).toString();
61
- }
62
- else if (pem === "PRIVATE KEY") {
63
- return raw_key.export({ format: "pem", type: "pkcs8" }).toString();
64
- }
65
- else {
66
- throw new Error("Unsupported case!");
67
- }
68
- }
69
- let pemType = identifyPemType(raw_key);
70
- if (pemType) {
71
- return raw_key instanceof Buffer ? raw_key.toString("utf8") : raw_key;
72
- }
73
- else {
74
- pemType = pem;
75
- assert(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
76
- let b = raw_key.toString("base64");
77
- let str = "-----BEGIN " + pemType + "-----\n";
78
- while (b.length) {
79
- str += b.substr(0, 64) + "\n";
80
- b = b.substr(64);
81
- }
82
- str += "-----END " + pemType + "-----";
83
- str += "\n";
84
- return str;
85
- }
86
- }
87
- exports.toPem = toPem;
88
- // istanbul ignore next
89
- function hexDump(buffer, width) {
90
- if (!buffer) {
91
- return "<>";
92
- }
93
- width = width || 32;
94
- if (buffer.length > 1024) {
95
- return (0, hexy_1.hexy)(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
96
- }
97
- else {
98
- return (0, hexy_1.hexy)(buffer, { width, format: "twos" });
99
- }
100
- }
101
- exports.hexDump = hexDump;
102
- function makeMessageChunkSignature(chunk, options) {
103
- // signature length = 128 bytes
104
- const signer = crypto.createSign(options.algorithm);
105
- signer.update(chunk);
106
- const signature = signer.sign(options.privateKey);
107
- assert(!options.signatureLength || signature.length === options.signatureLength);
108
- return signature;
109
- }
110
- exports.makeMessageChunkSignature = makeMessageChunkSignature;
111
- /**
112
- * @method verifyMessageChunkSignature
113
- *
114
- * const signer = {
115
- * signatureLength : 128,
116
- * algorithm : "RSA-SHA256",
117
- * publicKey: "qsdqsdqsd"
118
- * };
119
- * @param blockToVerify
120
- * @param signature
121
- * @param options
122
- * @param options.signatureLength
123
- * @param options.algorithm for example "RSA-SHA256"
124
- * @param options.publicKey
125
- * @return true if the signature is valid
126
- */
127
- function verifyMessageChunkSignature(blockToVerify, signature, options) {
128
- assert(blockToVerify instanceof Buffer);
129
- assert(signature instanceof Buffer);
130
- assert(typeof options.publicKey === "string");
131
- assert(identifyPemType(options.publicKey));
132
- const verify = crypto.createVerify(options.algorithm);
133
- verify.update(blockToVerify);
134
- return verify.verify(options.publicKey, signature);
135
- }
136
- exports.verifyMessageChunkSignature = verifyMessageChunkSignature;
137
- function makeSHA1Thumbprint(buffer) {
138
- return crypto.createHash("sha1").update(buffer).digest();
139
- }
140
- exports.makeSHA1Thumbprint = makeSHA1Thumbprint;
141
- // Basically when you =encrypt something using an RSA key (whether public or private), the encrypted value must
142
- // be smaller than the key (due to the maths used to do the actual encryption). So if you have a 1024-bit key,
143
- // in theory you could encrypt any 1023-bit value (or a 1024-bit value smaller than the key) with that key.
144
- // However, the PKCS#1 standard, which OpenSSL uses, specifies a padding scheme (so you can encrypt smaller
145
- // quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer
146
- // if the value you're encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit
147
- // key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag,
148
- // in which case you can go up to 1023-1024 bits). With a 2048-bit key it's 1960 bits instead.
149
- exports.RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
150
- exports.RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
151
- var PaddingAlgorithm;
152
- (function (PaddingAlgorithm) {
153
- PaddingAlgorithm[PaddingAlgorithm["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
154
- PaddingAlgorithm[PaddingAlgorithm["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
155
- })(PaddingAlgorithm = exports.PaddingAlgorithm || (exports.PaddingAlgorithm = {}));
156
- assert(PaddingAlgorithm.RSA_PKCS1_OAEP_PADDING === constants.RSA_PKCS1_OAEP_PADDING);
157
- assert(PaddingAlgorithm.RSA_PKCS1_PADDING === constants.RSA_PKCS1_PADDING);
158
- // publicEncrypt and privateDecrypt only work with
159
- // small buffer that depends of the key size.
160
- function publicEncrypt_native(buffer, publicKey, algorithm) {
161
- if (algorithm === undefined) {
162
- algorithm = PaddingAlgorithm.RSA_PKCS1_PADDING;
163
- }
164
- assert(algorithm === exports.RSA_PKCS1_PADDING || algorithm === exports.RSA_PKCS1_OAEP_PADDING);
165
- assert(buffer instanceof Buffer, "Expecting a buffer");
166
- return crypto.publicEncrypt({
167
- key: publicKey,
168
- padding: algorithm,
169
- }, buffer);
170
- }
171
- exports.publicEncrypt_native = publicEncrypt_native;
172
- function privateDecrypt_native(buffer, privateKey, algorithm) {
173
- if (algorithm === undefined) {
174
- algorithm = PaddingAlgorithm.RSA_PKCS1_PADDING;
175
- }
176
- assert(algorithm === exports.RSA_PKCS1_PADDING || algorithm === exports.RSA_PKCS1_OAEP_PADDING);
177
- assert(buffer instanceof Buffer, "Expecting a buffer");
178
- try {
179
- return crypto.privateDecrypt({
180
- key: privateKey,
181
- padding: algorithm,
182
- }, buffer);
183
- }
184
- catch (err) {
185
- return Buffer.alloc(1);
186
- }
187
- }
188
- exports.privateDecrypt_native = privateDecrypt_native;
189
- exports.publicEncrypt = publicEncrypt_native;
190
- exports.privateDecrypt = privateDecrypt_native;
191
- function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
192
- if (paddingAlgorithm === undefined) {
193
- paddingAlgorithm = PaddingAlgorithm.RSA_PKCS1_PADDING;
194
- }
195
- if (paddingAlgorithm !== exports.RSA_PKCS1_PADDING && paddingAlgorithm !== exports.RSA_PKCS1_OAEP_PADDING) {
196
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
197
- }
198
- const chunk_size = blockSize - padding;
199
- const nbBlocks = Math.ceil(buffer.length / chunk_size);
200
- const outputBuffer = (0, buffer_utils_1.createFastUninitializedBuffer)(nbBlocks * blockSize);
201
- for (let i = 0; i < nbBlocks; i++) {
202
- const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
203
- const encrypted_chunk = (0, exports.publicEncrypt)(currentBlock, publicKey, paddingAlgorithm);
204
- // istanbul ignore next
205
- if (encrypted_chunk.length !== blockSize) {
206
- throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
207
- }
208
- encrypted_chunk.copy(outputBuffer, i * blockSize);
209
- }
210
- return outputBuffer;
211
- }
212
- exports.publicEncrypt_long = publicEncrypt_long;
213
- function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
214
- paddingAlgorithm = paddingAlgorithm || exports.RSA_PKCS1_PADDING;
215
- // istanbul ignore next
216
- if (paddingAlgorithm !== exports.RSA_PKCS1_PADDING && paddingAlgorithm !== exports.RSA_PKCS1_OAEP_PADDING) {
217
- throw new Error("Invalid padding algorithm " + paddingAlgorithm);
218
- }
219
- const nbBlocks = Math.ceil(buffer.length / blockSize);
220
- const outputBuffer = (0, buffer_utils_1.createFastUninitializedBuffer)(nbBlocks * blockSize);
221
- let total_length = 0;
222
- for (let i = 0; i < nbBlocks; i++) {
223
- const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
224
- const decrypted_buf = (0, exports.privateDecrypt)(currentBlock, privateKey, paddingAlgorithm);
225
- decrypted_buf.copy(outputBuffer, total_length);
226
- total_length += decrypted_buf.length;
227
- }
228
- return outputBuffer.subarray(0, total_length);
229
- }
230
- exports.privateDecrypt_long = privateDecrypt_long;
231
- function coerceCertificatePem(certificate) {
232
- if (certificate instanceof Buffer) {
233
- certificate = toPem(certificate, "CERTIFICATE");
234
- }
235
- assert(typeof certificate === "string");
236
- return certificate;
237
- }
238
- exports.coerceCertificatePem = coerceCertificatePem;
239
- function coercePublicKeyPem(publicKey) {
240
- if (publicKey instanceof crypto.KeyObject) {
241
- return publicKey.export({ format: "pem", type: "spki" }).toString();
242
- }
243
- assert(typeof publicKey === "string");
244
- return publicKey;
245
- }
246
- exports.coercePublicKeyPem = coercePublicKeyPem;
247
- function coerceRsaPublicKeyPem(publicKey) {
248
- if (publicKey instanceof crypto.KeyObject) {
249
- return publicKey.export({ format: "pem", type: "spki" }).toString();
250
- }
251
- assert(typeof publicKey === "string");
252
- return publicKey;
253
- }
254
- exports.coerceRsaPublicKeyPem = coerceRsaPublicKeyPem;
255
- function coercePrivateKey(privateKey) {
256
- if (typeof privateKey === "string") {
257
- return crypto.createPrivateKey(privateKey);
258
- }
259
- return privateKey;
260
- }
261
- exports.coercePrivateKey = coercePrivateKey;
262
- function coercePrivateKeyPem(privateKey) {
263
- if (privateKey instanceof Buffer) {
264
- const o = crypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs1" });
265
- const e = o.export({ format: "der", type: "pkcs1" });
266
- privateKey = toPem(e, "RSA PRIVATE KEY");
267
- }
268
- assert(typeof privateKey === "string");
269
- return privateKey;
270
- }
271
- exports.coercePrivateKeyPem = coercePrivateKeyPem;
272
- /***
273
- * @method rsaLengthPrivateKey
274
- * A very expensive way to determine the rsa key length ( i.e 2048bits or 1024bits)
275
- * @param key a PEM public key or a PEM rsa private key
276
- * @return the key length in bytes.
277
- */
278
- function rsaLengthPrivateKey(key) {
279
- key = coercePrivateKey(key);
280
- // in node 16 and above :
281
- // return o.asymmetricKeyDetails.modulusLength/8
282
- // in node <16 :
283
- const key2 = key.export({ type: "pkcs1", format: "pem" }).toString();
284
- const a = jsrsasign.KEYUTIL.getKey(key2);
285
- return a.n.toString(16).length / 2;
286
- }
287
- exports.rsaLengthPrivateKey = rsaLengthPrivateKey;
288
- function rsaLengthPublicKey(key) {
289
- key = coercePublicKeyPem(key);
290
- assert(typeof key === "string");
291
- const a = jsrsasign.KEYUTIL.getKey(key);
292
- return a.n.toString(16).length / 2;
293
- }
294
- exports.rsaLengthPublicKey = rsaLengthPublicKey;
295
- function rsaLengthRsaPublicKey(key) {
296
- key = coerceRsaPublicKeyPem(key);
297
- assert(typeof key === "string");
298
- const a = jsrsasign.KEYUTIL.getKey(key);
299
- return a.n.toString(16).length / 2;
300
- }
301
- exports.rsaLengthRsaPublicKey = rsaLengthRsaPublicKey;
302
- function extractPublicKeyFromCertificateSync(certificate) {
303
- certificate = coerceCertificatePem(certificate);
304
- const key = jsrsasign.KEYUTIL.getKey(certificate);
305
- const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
306
- assert(typeof publicKeyAsPem === "string");
307
- return publicKeyAsPem;
308
- }
309
- exports.extractPublicKeyFromCertificateSync = extractPublicKeyFromCertificateSync;
310
- // https://github.com/kjur/jsrsasign/blob/master/x509-1.1.js
311
- // tool to analyse asn1 base64 blocks : http://lapo.it/asn1js
312
- /**
313
- * extract the publickey from a certificate
314
- * @async
315
- */
316
- function extractPublicKeyFromCertificate(certificate, callback) {
317
- let err1 = null;
318
- let keyPem;
319
- try {
320
- keyPem = extractPublicKeyFromCertificateSync(certificate);
321
- }
322
- catch (err) {
323
- err1 = err;
324
- }
325
- setImmediate(() => {
326
- callback(err1, keyPem);
327
- });
328
- }
329
- exports.extractPublicKeyFromCertificate = extractPublicKeyFromCertificate;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractPublicKeyFromCertificate = exports.extractPublicKeyFromCertificateSync = exports.rsaLengthRsaPublicKey = exports.rsaLengthPublicKey = exports.rsaLengthPrivateKey = exports.coercePrivateKeyPem = exports.coercePrivateKey = exports.coerceRsaPublicKeyPem = exports.coercePublicKeyPem = exports.coerceCertificatePem = exports.privateDecrypt_long = exports.publicEncrypt_long = exports.privateDecrypt = exports.publicEncrypt = exports.privateDecrypt_native = exports.publicEncrypt_native = exports.PaddingAlgorithm = exports.RSA_PKCS1_PADDING = exports.RSA_PKCS1_OAEP_PADDING = exports.makeSHA1Thumbprint = exports.verifyMessageChunkSignature = exports.makeMessageChunkSignature = exports.hexDump = exports.toPem = exports.convertPEMtoDER = exports.identifyPemType = void 0;
4
+ // tslint:disabled:no-var-requires
5
+ /**
6
+ * @module node_opcua_crypto
7
+ */
8
+ const constants = require("constants");
9
+ const crypto = require("crypto");
10
+ const buffer_utils_1 = require("./buffer_utils");
11
+ const crypto_explore_certificate_1 = require("./crypto_explore_certificate");
12
+ const assert = require("assert");
13
+ const hexy_1 = require("hexy");
14
+ const jsrsasign = require("jsrsasign");
15
+ const PEM_REGEX = /^(-----BEGIN (.*)-----\r?\n([/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2-----\r?\n?)/gm;
16
+ const PEM_TYPE_REGEX = /^(-----BEGIN (.*)-----)/m;
17
+ // Copyright 2012 The Obvious Corporation.
18
+ // identifyPemType
19
+ /*=
20
+ * Extract and identify the PEM file type represented in the given
21
+ * buffer. Returns the extracted type string or undefined if the
22
+ * buffer doesn't seem to be any sort of PEM format file.
23
+ */
24
+ function identifyPemType(rawKey) {
25
+ if (rawKey instanceof Buffer) {
26
+ rawKey = rawKey.toString("utf8");
27
+ }
28
+ const match = PEM_TYPE_REGEX.exec(rawKey);
29
+ return !match ? undefined : match[2];
30
+ }
31
+ exports.identifyPemType = identifyPemType;
32
+ function convertPEMtoDER(raw_key) {
33
+ let match;
34
+ let pemType;
35
+ let base64str;
36
+ const parts = [];
37
+ PEM_REGEX.lastIndex = 0;
38
+ // tslint:disable-next-line:no-conditional-assignment
39
+ while ((match = PEM_REGEX.exec(raw_key)) !== null) {
40
+ pemType = match[2];
41
+ // pemType shall be "RSA PRIVATE KEY" , "PUBLIC KEY", "CERTIFICATE", "X509 CRL"
42
+ base64str = match[3];
43
+ base64str = base64str.replace(/\r?\n/g, "");
44
+ parts.push(Buffer.from(base64str, "base64"));
45
+ }
46
+ return (0, crypto_explore_certificate_1.combine_der)(parts);
47
+ }
48
+ exports.convertPEMtoDER = convertPEMtoDER;
49
+ /**
50
+ * @method toPem
51
+ * @param raw_key
52
+ * @param pem
53
+ * @return
54
+ */
55
+ function toPem(raw_key, pem) {
56
+ assert(raw_key, "expecting a key");
57
+ assert(typeof pem === "string");
58
+ if (raw_key instanceof crypto.KeyObject) {
59
+ if (pem === "RSA PRIVATE KEY") {
60
+ return raw_key.export({ format: "pem", type: "pkcs1" }).toString();
61
+ }
62
+ else if (pem === "PRIVATE KEY") {
63
+ return raw_key.export({ format: "pem", type: "pkcs8" }).toString();
64
+ }
65
+ else {
66
+ throw new Error("Unsupported case!");
67
+ }
68
+ }
69
+ let pemType = identifyPemType(raw_key);
70
+ if (pemType) {
71
+ return raw_key instanceof Buffer ? raw_key.toString("utf8") : raw_key;
72
+ }
73
+ else {
74
+ pemType = pem;
75
+ assert(["CERTIFICATE REQUEST", "CERTIFICATE", "RSA PRIVATE KEY", "PUBLIC KEY", "X509 CRL"].indexOf(pemType) >= 0);
76
+ let b = raw_key.toString("base64");
77
+ let str = "-----BEGIN " + pemType + "-----\n";
78
+ while (b.length) {
79
+ str += b.substr(0, 64) + "\n";
80
+ b = b.substr(64);
81
+ }
82
+ str += "-----END " + pemType + "-----";
83
+ str += "\n";
84
+ return str;
85
+ }
86
+ }
87
+ exports.toPem = toPem;
88
+ // istanbul ignore next
89
+ function hexDump(buffer, width) {
90
+ if (!buffer) {
91
+ return "<>";
92
+ }
93
+ width = width || 32;
94
+ if (buffer.length > 1024) {
95
+ return (0, hexy_1.hexy)(buffer.subarray(0, 1024), { width, format: "twos" }) + "\n .... ( " + buffer.length + ")";
96
+ }
97
+ else {
98
+ return (0, hexy_1.hexy)(buffer, { width, format: "twos" });
99
+ }
100
+ }
101
+ exports.hexDump = hexDump;
102
+ function makeMessageChunkSignature(chunk, options) {
103
+ // signature length = 128 bytes
104
+ const signer = crypto.createSign(options.algorithm);
105
+ signer.update(chunk);
106
+ const signature = signer.sign(options.privateKey);
107
+ assert(!options.signatureLength || signature.length === options.signatureLength);
108
+ return signature;
109
+ }
110
+ exports.makeMessageChunkSignature = makeMessageChunkSignature;
111
+ /**
112
+ * @method verifyMessageChunkSignature
113
+ *
114
+ * const signer = {
115
+ * signatureLength : 128,
116
+ * algorithm : "RSA-SHA256",
117
+ * publicKey: "qsdqsdqsd"
118
+ * };
119
+ * @param blockToVerify
120
+ * @param signature
121
+ * @param options
122
+ * @param options.signatureLength
123
+ * @param options.algorithm for example "RSA-SHA256"
124
+ * @param options.publicKey
125
+ * @return true if the signature is valid
126
+ */
127
+ function verifyMessageChunkSignature(blockToVerify, signature, options) {
128
+ assert(blockToVerify instanceof Buffer);
129
+ assert(signature instanceof Buffer);
130
+ assert(typeof options.publicKey === "string");
131
+ assert(identifyPemType(options.publicKey));
132
+ const verify = crypto.createVerify(options.algorithm);
133
+ verify.update(blockToVerify);
134
+ return verify.verify(options.publicKey, signature);
135
+ }
136
+ exports.verifyMessageChunkSignature = verifyMessageChunkSignature;
137
+ function makeSHA1Thumbprint(buffer) {
138
+ return crypto.createHash("sha1").update(buffer).digest();
139
+ }
140
+ exports.makeSHA1Thumbprint = makeSHA1Thumbprint;
141
+ // Basically when you =encrypt something using an RSA key (whether public or private), the encrypted value must
142
+ // be smaller than the key (due to the maths used to do the actual encryption). So if you have a 1024-bit key,
143
+ // in theory you could encrypt any 1023-bit value (or a 1024-bit value smaller than the key) with that key.
144
+ // However, the PKCS#1 standard, which OpenSSL uses, specifies a padding scheme (so you can encrypt smaller
145
+ // quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer
146
+ // if the value you're encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit
147
+ // key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag,
148
+ // in which case you can go up to 1023-1024 bits). With a 2048-bit key it's 1960 bits instead.
149
+ exports.RSA_PKCS1_OAEP_PADDING = constants.RSA_PKCS1_OAEP_PADDING;
150
+ exports.RSA_PKCS1_PADDING = constants.RSA_PKCS1_PADDING;
151
+ var PaddingAlgorithm;
152
+ (function (PaddingAlgorithm) {
153
+ PaddingAlgorithm[PaddingAlgorithm["RSA_PKCS1_OAEP_PADDING"] = 4] = "RSA_PKCS1_OAEP_PADDING";
154
+ PaddingAlgorithm[PaddingAlgorithm["RSA_PKCS1_PADDING"] = 1] = "RSA_PKCS1_PADDING";
155
+ })(PaddingAlgorithm = exports.PaddingAlgorithm || (exports.PaddingAlgorithm = {}));
156
+ assert(PaddingAlgorithm.RSA_PKCS1_OAEP_PADDING === constants.RSA_PKCS1_OAEP_PADDING);
157
+ assert(PaddingAlgorithm.RSA_PKCS1_PADDING === constants.RSA_PKCS1_PADDING);
158
+ // publicEncrypt and privateDecrypt only work with
159
+ // small buffer that depends of the key size.
160
+ function publicEncrypt_native(buffer, publicKey, algorithm) {
161
+ if (algorithm === undefined) {
162
+ algorithm = PaddingAlgorithm.RSA_PKCS1_PADDING;
163
+ }
164
+ assert(algorithm === exports.RSA_PKCS1_PADDING || algorithm === exports.RSA_PKCS1_OAEP_PADDING);
165
+ assert(buffer instanceof Buffer, "Expecting a buffer");
166
+ return crypto.publicEncrypt({
167
+ key: publicKey,
168
+ padding: algorithm,
169
+ }, buffer);
170
+ }
171
+ exports.publicEncrypt_native = publicEncrypt_native;
172
+ function privateDecrypt_native(buffer, privateKey, algorithm) {
173
+ if (algorithm === undefined) {
174
+ algorithm = PaddingAlgorithm.RSA_PKCS1_PADDING;
175
+ }
176
+ assert(algorithm === exports.RSA_PKCS1_PADDING || algorithm === exports.RSA_PKCS1_OAEP_PADDING);
177
+ assert(buffer instanceof Buffer, "Expecting a buffer");
178
+ try {
179
+ return crypto.privateDecrypt({
180
+ key: privateKey,
181
+ padding: algorithm,
182
+ }, buffer);
183
+ }
184
+ catch (err) {
185
+ return Buffer.alloc(1);
186
+ }
187
+ }
188
+ exports.privateDecrypt_native = privateDecrypt_native;
189
+ exports.publicEncrypt = publicEncrypt_native;
190
+ exports.privateDecrypt = privateDecrypt_native;
191
+ function publicEncrypt_long(buffer, publicKey, blockSize, padding, paddingAlgorithm) {
192
+ if (paddingAlgorithm === undefined) {
193
+ paddingAlgorithm = PaddingAlgorithm.RSA_PKCS1_PADDING;
194
+ }
195
+ if (paddingAlgorithm !== exports.RSA_PKCS1_PADDING && paddingAlgorithm !== exports.RSA_PKCS1_OAEP_PADDING) {
196
+ throw new Error("Invalid padding algorithm " + paddingAlgorithm);
197
+ }
198
+ const chunk_size = blockSize - padding;
199
+ const nbBlocks = Math.ceil(buffer.length / chunk_size);
200
+ const outputBuffer = (0, buffer_utils_1.createFastUninitializedBuffer)(nbBlocks * blockSize);
201
+ for (let i = 0; i < nbBlocks; i++) {
202
+ const currentBlock = buffer.subarray(chunk_size * i, chunk_size * (i + 1));
203
+ const encrypted_chunk = (0, exports.publicEncrypt)(currentBlock, publicKey, paddingAlgorithm);
204
+ // istanbul ignore next
205
+ if (encrypted_chunk.length !== blockSize) {
206
+ throw new Error(`publicEncrypt_long unexpected chunk length ${encrypted_chunk.length} expecting ${blockSize}`);
207
+ }
208
+ encrypted_chunk.copy(outputBuffer, i * blockSize);
209
+ }
210
+ return outputBuffer;
211
+ }
212
+ exports.publicEncrypt_long = publicEncrypt_long;
213
+ function privateDecrypt_long(buffer, privateKey, blockSize, paddingAlgorithm) {
214
+ paddingAlgorithm = paddingAlgorithm || exports.RSA_PKCS1_PADDING;
215
+ // istanbul ignore next
216
+ if (paddingAlgorithm !== exports.RSA_PKCS1_PADDING && paddingAlgorithm !== exports.RSA_PKCS1_OAEP_PADDING) {
217
+ throw new Error("Invalid padding algorithm " + paddingAlgorithm);
218
+ }
219
+ const nbBlocks = Math.ceil(buffer.length / blockSize);
220
+ const outputBuffer = (0, buffer_utils_1.createFastUninitializedBuffer)(nbBlocks * blockSize);
221
+ let total_length = 0;
222
+ for (let i = 0; i < nbBlocks; i++) {
223
+ const currentBlock = buffer.subarray(blockSize * i, Math.min(blockSize * (i + 1), buffer.length));
224
+ const decrypted_buf = (0, exports.privateDecrypt)(currentBlock, privateKey, paddingAlgorithm);
225
+ decrypted_buf.copy(outputBuffer, total_length);
226
+ total_length += decrypted_buf.length;
227
+ }
228
+ return outputBuffer.subarray(0, total_length);
229
+ }
230
+ exports.privateDecrypt_long = privateDecrypt_long;
231
+ function coerceCertificatePem(certificate) {
232
+ if (certificate instanceof Buffer) {
233
+ certificate = toPem(certificate, "CERTIFICATE");
234
+ }
235
+ assert(typeof certificate === "string");
236
+ return certificate;
237
+ }
238
+ exports.coerceCertificatePem = coerceCertificatePem;
239
+ function coercePublicKeyPem(publicKey) {
240
+ if (publicKey instanceof crypto.KeyObject) {
241
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
242
+ }
243
+ assert(typeof publicKey === "string");
244
+ return publicKey;
245
+ }
246
+ exports.coercePublicKeyPem = coercePublicKeyPem;
247
+ function coerceRsaPublicKeyPem(publicKey) {
248
+ if (publicKey instanceof crypto.KeyObject) {
249
+ return publicKey.export({ format: "pem", type: "spki" }).toString();
250
+ }
251
+ assert(typeof publicKey === "string");
252
+ return publicKey;
253
+ }
254
+ exports.coerceRsaPublicKeyPem = coerceRsaPublicKeyPem;
255
+ function coercePrivateKey(privateKey) {
256
+ if (typeof privateKey === "string") {
257
+ return crypto.createPrivateKey(privateKey);
258
+ }
259
+ return privateKey;
260
+ }
261
+ exports.coercePrivateKey = coercePrivateKey;
262
+ function coercePrivateKeyPem(privateKey) {
263
+ if (privateKey instanceof Buffer) {
264
+ const o = crypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs1" });
265
+ const e = o.export({ format: "der", type: "pkcs1" });
266
+ privateKey = toPem(e, "RSA PRIVATE KEY");
267
+ }
268
+ assert(typeof privateKey === "string");
269
+ return privateKey;
270
+ }
271
+ exports.coercePrivateKeyPem = coercePrivateKeyPem;
272
+ /***
273
+ * @method rsaLengthPrivateKey
274
+ * A very expensive way to determine the rsa key length ( i.e 2048bits or 1024bits)
275
+ * @param key a PEM public key or a PEM rsa private key
276
+ * @return the key length in bytes.
277
+ */
278
+ function rsaLengthPrivateKey(key) {
279
+ key = coercePrivateKey(key);
280
+ // in node 16 and above :
281
+ // return o.asymmetricKeyDetails.modulusLength/8
282
+ // in node <16 :
283
+ const key2 = key.export({ type: "pkcs1", format: "pem" }).toString();
284
+ const a = jsrsasign.KEYUTIL.getKey(key2);
285
+ return a.n.toString(16).length / 2;
286
+ }
287
+ exports.rsaLengthPrivateKey = rsaLengthPrivateKey;
288
+ function rsaLengthPublicKey(key) {
289
+ key = coercePublicKeyPem(key);
290
+ assert(typeof key === "string");
291
+ const a = jsrsasign.KEYUTIL.getKey(key);
292
+ return a.n.toString(16).length / 2;
293
+ }
294
+ exports.rsaLengthPublicKey = rsaLengthPublicKey;
295
+ function rsaLengthRsaPublicKey(key) {
296
+ key = coerceRsaPublicKeyPem(key);
297
+ assert(typeof key === "string");
298
+ const a = jsrsasign.KEYUTIL.getKey(key);
299
+ return a.n.toString(16).length / 2;
300
+ }
301
+ exports.rsaLengthRsaPublicKey = rsaLengthRsaPublicKey;
302
+ function extractPublicKeyFromCertificateSync(certificate) {
303
+ certificate = coerceCertificatePem(certificate);
304
+ const key = jsrsasign.KEYUTIL.getKey(certificate);
305
+ const publicKeyAsPem = jsrsasign.KEYUTIL.getPEM(key);
306
+ assert(typeof publicKeyAsPem === "string");
307
+ return publicKeyAsPem;
308
+ }
309
+ exports.extractPublicKeyFromCertificateSync = extractPublicKeyFromCertificateSync;
310
+ // https://github.com/kjur/jsrsasign/blob/master/x509-1.1.js
311
+ // tool to analyse asn1 base64 blocks : http://lapo.it/asn1js
312
+ /**
313
+ * extract the publickey from a certificate
314
+ * @async
315
+ */
316
+ function extractPublicKeyFromCertificate(certificate, callback) {
317
+ let err1 = null;
318
+ let keyPem;
319
+ try {
320
+ keyPem = extractPublicKeyFromCertificateSync(certificate);
321
+ }
322
+ catch (err) {
323
+ err1 = err;
324
+ }
325
+ setImmediate(() => {
326
+ callback(err1, keyPem);
327
+ });
328
+ }
329
+ exports.extractPublicKeyFromCertificate = extractPublicKeyFromCertificate;
330
330
  //# sourceMappingURL=crypto_utils.js.map