-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
pem.js
1519 lines (1340 loc) · 45.9 KB
/
pem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
/**
* pem module
*
* @module pem
*/
const {debug} = require('./debug.js')
const {promisify} = require('es6-promisify')
var net = require('net')
var helper = require('./helper.js')
var openssl = require('./openssl.js')
const hash_md5 = require("md5")
module.exports.createPrivateKey = createPrivateKey
module.exports.createDhparam = createDhparam
module.exports.createEcparam = createEcparam
module.exports.createCSR = createCSR
module.exports.createCertificate = createCertificate
module.exports.readCertificateInfo = readCertificateInfo
module.exports.getPublicKey = getPublicKey
module.exports.getFingerprint = getFingerprint
module.exports.getModulus = getModulus
module.exports.getDhparamInfo = getDhparamInfo
module.exports.createPkcs12 = createPkcs12
module.exports.readPkcs12 = readPkcs12
module.exports.verifySigningChain = verifySigningChain
module.exports.checkCertificate = checkCertificate
module.exports.checkPkcs12 = checkPkcs12
module.exports.config = config
/**
* quick access the convert module
* @type {module:convert}
*/
module.exports.convert = require('./convert.js')
var KEY_START = '-----BEGIN PRIVATE KEY-----'
var KEY_END = '-----END PRIVATE KEY-----'
var RSA_KEY_START = '-----BEGIN RSA PRIVATE KEY-----'
var RSA_KEY_END = '-----END RSA PRIVATE KEY-----'
var ENCRYPTED_KEY_START = '-----BEGIN ENCRYPTED PRIVATE KEY-----'
var ENCRYPTED_KEY_END = '-----END ENCRYPTED PRIVATE KEY-----'
var CERT_START = '-----BEGIN CERTIFICATE-----'
var CERT_END = '-----END CERTIFICATE-----'
/**
* Creates a private key
*
* @static
* @param {Number} [keyBitsize=2048] Size of the key, defaults to 2048bit
* @param {Object} [options] object of cipher and password {cipher:'aes128',password:'xxx'}, defaults empty object
* @param {String} [options.cipher] string of the cipher for the encryption - needed with password
* @param {String} [options.password] string of the cipher password for the encryption needed with cipher
* @param {Function} callback Callback function with an error object and {key}
*/
function createPrivateKey(keyBitsize, options, callback) {
if (!callback && !options && typeof keyBitsize === 'function') {
callback = keyBitsize
keyBitsize = undefined
options = {}
} else if (!callback && keyBitsize && typeof options === 'function') {
callback = options
options = {}
}
keyBitsize = Number(keyBitsize) || 2048
var params = ['genrsa']
if (openssl.get('Vendor') === 'OPENSSL' && openssl.get('VendorVersionMajor') >= 3) {
params.push('-traditional')
}
var delTempPWFiles = []
if (options && options.cipher && (Number(helper.ciphers.indexOf(options.cipher)) !== -1) && options.password) {
debug('helper.createPasswordFile', {
cipher: options.cipher,
password: options.password,
passType: 'out'
})
helper.createPasswordFile({
cipher: options.cipher,
password: options.password,
passType: 'out'
}, params, delTempPWFiles)
}
params.push(keyBitsize)
debug('version', openssl.get('openSslVersion'))
openssl.exec(params, '(RSA |ENCRYPTED |)PRIVATE KEY', function (sslErr, key) {
function done(err) {
if (err) {
return callback(err)
}
return callback(null, {
key: key
})
}
helper.deleteTempFiles(delTempPWFiles, function (fsErr) {
debug('createPrivateKey', {
sslErr: sslErr,
fsErr: fsErr,
key: key,
keyLength: key && key.length
})
done(sslErr || fsErr)
})
})
}
/**
* Creates a dhparam key
*
* @static
* @param {Number} [keyBitsize=512] Size of the key, defaults to 512bit
* @param {Function} callback Callback function with an error object and {dhparam}
*/
function createDhparam(keyBitsize, callback) {
if (!callback && typeof keyBitsize === 'function') {
callback = keyBitsize
keyBitsize = undefined
}
keyBitsize = Number(keyBitsize) || 512
var params = ['dhparam',
'-outform',
'PEM',
keyBitsize
]
openssl.exec(params, 'DH PARAMETERS', function (error, dhparam) {
if (error) {
return callback(error)
}
return callback(null, {
dhparam: dhparam
})
})
}
/**
* Creates a ecparam key
* @static
* @param {String} [keyName=secp256k1] Name of the key, defaults to secp256k1
* @param {String} [paramEnc=explicit] Encoding of the elliptic curve parameters, defaults to explicit
* @param {Boolean} [noOut=false] This option inhibits the output of the encoded version of the parameters.
* @param {Function} callback Callback function with an error object and {ecparam}
*/
function createEcparam(keyName, paramEnc, noOut, callback) {
if (!callback && typeof noOut === 'undefined' && !paramEnc && typeof keyName === 'function') {
callback = keyName
keyName = undefined
} else if (!callback && typeof noOut === 'undefined' && keyName && typeof paramEnc === 'function') {
callback = paramEnc
paramEnc = undefined
} else if (!callback && typeof noOut === 'function' && keyName && paramEnc) {
callback = noOut
noOut = undefined
}
keyName = keyName || 'secp256k1'
paramEnc = paramEnc || 'explicit'
noOut = noOut || false
var params = ['ecparam',
'-name',
keyName,
'-genkey',
'-param_enc',
paramEnc
]
var searchString = 'EC PARAMETERS'
if (noOut) {
params.push('-noout')
searchString = 'EC PRIVATE KEY'
}
openssl.exec(params, searchString, function (error, ecparam) {
if (error) {
return callback(error)
}
return callback(null, {
ecparam: ecparam
})
})
}
/**
* Creates a Certificate Signing Request
* If client key is undefined, a new key is created automatically. The used key is included
* in the callback return as clientKey
* @static
* @param {Object} [options] Optional options object
* @param {String} [options.clientKey] Optional client key to use
* @param {Number} [options.keyBitsize] If clientKey is undefined, bit size to use for generating a new key (defaults to 2048)
* @param {String} [options.hash] Hash function to use (either md5 sha1 or sha256, defaults to sha256)
* @param {String} [options.country] CSR country field
* @param {String} [options.state] CSR state field
* @param {String} [options.locality] CSR locality field
* @param {String} [options.organization] CSR organization field
* @param {String} [options.organizationUnit] CSR organizational unit field
* @param {String} [options.commonName='localhost'] CSR common name field
* @param {String} [options.emailAddress] CSR email address field
* @param {String} [options.csrConfigFile] CSR config file
* @param {Array} [options.altNames] is a list of subjectAltNames in the subjectAltName field
* @param {Function} callback Callback function with an error object and {csr, clientKey}
*/
function createCSR(options, callback) {
if (!callback && typeof options === 'function') {
callback = options
options = undefined
}
let delTempPWFiles = []
options = options || {}
// http://stackoverflow.com/questions/14089872/why-does-node-js-accept-ip-addresses-in-certificates-only-for-san-not-for-cn
if (options.commonName && (net.isIPv4(options.commonName) || net.isIPv6(options.commonName))) {
if (!options.altNames) {
options.altNames = [options.commonName]
} else if (options.altNames.indexOf(options.commonName) === -1) {
options.altNames = options.altNames.concat([options.commonName])
}
}
if (!options.clientKey) {
if (options && (options.password || options.clientKeyPassword)) {
options.password = options.password || options.clientKeyPassword || ''
}
createPrivateKey(options.keyBitsize || 2048, options, function (error, keyData) {
if (error) {
return callback(error)
}
options.clientKey = keyData.key
createCSR(options, callback)
})
return
}
var params = ['req',
'-new',
'-' + (options.hash || 'sha256')
]
if (options.csrConfigFile) {
params.push('-config')
params.push(options.csrConfigFile)
} else {
params.push('-subj')
params.push(generateCSRSubject(options))
}
params.push('-key')
params.push('--TMPFILE--')
var tmpfiles = [options.clientKey]
var config = null
if (options && (options.password || options.clientKeyPassword)) {
helper.createPasswordFile({
cipher: '',
password: options.password || options.clientKeyPassword,
passType: 'in'
}, params, delTempPWFiles)
}
if (options.altNames && Array.isArray(options.altNames) && options.altNames.length) {
params.push('-extensions')
params.push('v3_req')
params.push('-config')
params.push('--TMPFILE--')
var altNamesRep = []
for (var i = 0; i < options.altNames.length; i++) {
altNamesRep.push((net.isIP(options.altNames[i]) ? 'IP' : 'DNS') + '.' + (i + 1) + ' = ' + options.altNames[i])
}
tmpfiles.push(config = [
'[req]',
'req_extensions = v3_req',
'distinguished_name = req_distinguished_name',
'[v3_req]',
'subjectAltName = @alt_names',
'[alt_names]',
altNamesRep.join('\n'),
'[req_distinguished_name]',
'commonName = Common Name',
'commonName_max = 64'
].join('\n'))
} else if (options.config) {
config = options.config
}
if (options.clientKeyPassword) {
helper.createPasswordFile({
cipher: '',
password: options.clientKeyPassword,
passType: 'in'
}, params, delTempPWFiles)
}
openssl.exec(params, 'CERTIFICATE REQUEST', tmpfiles, function (sslErr, data) {
function done(err) {
if (err) {
return callback(err)
}
callback(null, {
csr: data,
config: config,
clientKey: options.clientKey
})
}
helper.deleteTempFiles(delTempPWFiles, function (fsErr) {
done(sslErr || fsErr)
})
})
}
/**
* Creates a certificate based on a CSR. If CSR is not defined, a new one
* will be generated automatically. For CSR generation all the options values
* can be used as with createCSR.
* @static
* @param {Object} [options] Optional options object
* @param {String} [options.serviceCertificate] PEM encoded certificate
* @param {String} [options.serviceKey] Private key for signing the certificate, if not defined a new one is generated
* @param {String} [options.serviceKeyPassword] Password of the service key
* @param {Boolean} [options.selfSigned] If set to true and serviceKey is not defined, use clientKey for signing
* @param {String|Number} [options.serial] Set a serial max. 20 octets - only together with options.serviceCertificate
* @param {String} [options.serialFile] Set the name of the serial file, without extension. - only together with options.serviceCertificate and never in tandem with options.serial
* @param {String} [options.hash] Hash function to use (either md5 sha1 or sha256, defaults to sha256)
* @param {String} [options.csr] CSR for the certificate, if not defined a new one is generated
* @param {Number} [options.days] Certificate expire time in days
* @param {String} [options.clientKeyPassword] Password of the client key
* @param {String} [options.extFile] extension config file - without '-extensions v3_req'
* @param {String} [options.config] extension config file - with '-extensions v3_req'
* @param {String} [options.csrConfigFile] CSR config file - only used if no options.csr is provided
* @param {Array} [options.altNames] is a list of subjectAltNames in the subjectAltName field - only used if no options.csr is provided
* @param {Function} callback Callback function with an error object and {certificate, csr, clientKey, serviceKey}
*/
function createCertificate(options, callback) {
if (!callback && typeof options === 'function') {
callback = options
options = undefined
}
options = options || {}
if (!options.csr) {
createCSR(options, function (error, keyData) {
if (error) {
return callback(error)
}
options.csr = keyData.csr
options.config = keyData.config
options.clientKey = keyData.clientKey
createCertificate(options, callback)
})
return
}
if (!options.clientKey) {
options.clientKey = ''
}
if (!options.serviceKey) {
if (options.selfSigned) {
options.serviceKey = options.clientKey
} else {
createPrivateKey(options.keyBitsize || 2048, {
cipher: options.cipher,
password: options.clientKeyPassword || ''
}, function (error, keyData) {
if (error) {
return callback(error)
}
options.serviceKey = keyData.key
createCertificate(options, callback)
})
return
}
}
readCertificateInfo(options.csr, function (error2, data2) {
if (error2) {
return callback(error2)
}
var params = ['x509',
'-req',
'-' + (options.hash || 'sha256'),
'-days',
Number(options.days) || '365',
'-in',
'--TMPFILE--'
]
var tmpfiles = [options.csr]
var delTempPWFiles = []
if (options.serviceCertificate) {
params.push('-CA')
params.push('--TMPFILE--')
params.push('-CAkey')
params.push('--TMPFILE--')
if (options.serial) {
params.push('-set_serial')
if (helper.isNumber(options.serial)) {
// set the serial to the max lenth of 20 octets ()
// A certificate serial number is not decimal conforming. That is the
// bytes in a serial number do not necessarily map to a printable ASCII
// character.
// eg: 0x00 is a valid serial number and can not be represented in a
// human readable format (atleast one that can be directly mapped to
// the ACSII table).
params.push('0x' + ('0000000000000000000000000000000000000000' + options.serial.toString(16)).slice(-40))
} else {
if (helper.isHex(options.serial)) {
if (options.serial.startsWith('0x')) {
options.serial = options.serial.substring(2, options.serial.length)
}
params.push('0x' + ('0000000000000000000000000000000000000000' + options.serial).slice(-40))
} else {
params.push('0x' + ('0000000000000000000000000000000000000000' + helper.toHex(options.serial)).slice(-40))
}
}
} else {
params.push('-CAcreateserial')
if (options.serialFile) {
params.push('-CAserial')
params.push(options.serialFile + '.srl')
}
}
if (options.serviceKeyPassword) {
helper.createPasswordFile({
cipher: '',
password: options.serviceKeyPassword,
passType: 'in'
}, params, delTempPWFiles)
}
tmpfiles.push(options.serviceCertificate)
tmpfiles.push(options.serviceKey)
} else {
params.push('-signkey')
params.push('--TMPFILE--')
if (options.serviceKeyPassword) {
helper.createPasswordFile({
cipher: '',
password: options.serviceKeyPassword,
passType: 'in'
}, params, delTempPWFiles)
}
tmpfiles.push(options.serviceKey)
}
if (options.config) {
params.push('-extensions')
params.push('v3_req')
params.push('-extfile')
params.push('--TMPFILE--')
tmpfiles.push(options.config)
} else if (options.extFile) {
params.push('-extfile')
params.push(options.extFile)
} else {
var altNamesRep = []
if (data2 && data2.san) {
for (var i = 0; i < data2.san.dns.length; i++) {
altNamesRep.push('DNS' + '.' + (i + 1) + ' = ' + data2.san.dns[i])
}
for (var i2 = 0; i2 < data2.san.ip.length; i2++) {
altNamesRep.push('IP' + '.' + (i2 + 1) + ' = ' + data2.san.ip[i2])
}
for (var i3 = 0; i3 < data2.san.email.length; i3++) {
altNamesRep.push('email' + '.' + (i3 + 1) + ' = ' + data2.san.email[i3])
}
params.push('-extensions')
params.push('v3_req')
params.push('-extfile')
params.push('--TMPFILE--')
tmpfiles.push([
'[v3_req]',
'subjectAltName = @alt_names',
'[alt_names]',
altNamesRep.join('\n')
].join('\n'))
}
}
if (options.clientKeyPassword) {
helper.createPasswordFile({
cipher: '',
password: options.clientKeyPassword,
passType: 'in'
}, params, delTempPWFiles)
}
openssl.exec(params, 'CERTIFICATE', tmpfiles, function (sslErr, data) {
function done(err) {
if (err) {
return callback(err)
}
var response = {
csr: options.csr,
clientKey: options.clientKey,
certificate: data,
serviceKey: options.serviceKey
}
return callback(null, response)
}
helper.deleteTempFiles(delTempPWFiles, function (fsErr) {
done(sslErr || fsErr)
})
})
})
}
/**
* Exports a public key from a private key, CSR or certificate
* @static
* @param {String} certificate PEM encoded private key, CSR or certificate
* @param {Function} callback Callback function with an error object and {publicKey}
*/
function getPublicKey(certificate, callback) {
if (!callback && typeof certificate === 'function') {
callback = certificate
certificate = undefined
}
certificate = (certificate || '').toString()
var params
if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) {
params = ['req',
'-in',
'--TMPFILE--',
'-pubkey',
'-noout'
]
} else if (certificate.match(/BEGIN RSA PRIVATE KEY/) || certificate.match(/BEGIN PRIVATE KEY/)) {
params = ['rsa',
'-in',
'--TMPFILE--',
'-pubout'
]
} else {
params = ['x509',
'-in',
'--TMPFILE--',
'-pubkey',
'-noout'
]
}
openssl.exec(params, 'PUBLIC KEY', certificate, function (error, key) {
if (error) {
return callback(error)
}
return callback(null, {
publicKey: key
})
})
}
/**
* Reads subject data from a certificate or a CSR
* @static
* @param {String} certificate PEM encoded CSR or certificate
* @param {Function} callback Callback function with an error object and {country, state, locality, organization, organizationUnit, commonName, emailAddress}
*/
function readCertificateInfo(certificate, callback) {
if (!callback && typeof certificate === 'function') {
callback = certificate
certificate = undefined
}
certificate = (certificate || '').toString()
var isMatch = certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)
var type = isMatch ? 'req' : 'x509'
var params = [type,
'-noout',
'-nameopt',
'RFC2253,sep_multiline,space_eq,-esc_msb,utf8',
'-text',
'-in',
'--TMPFILE--'
]
openssl.spawnWrapper(params, certificate, function (err, code, stdout, stderr) {
if (err) {
return callback(err)
} else if (stderr) {
return callback(stderr)
}
return fetchCertificateData(stdout, callback)
})
}
/**
* get the modulus from a certificate, a CSR or a private key
* @static
* @param {String} certificate PEM encoded, CSR PEM encoded, or private key
* @param {String} [password] password for the certificate
* @param {String} [hash] hash function to use (up to now `md5` supported) (default: none)
* @param {Function} callback Callback function with an error object and {modulus}
*/
function getModulus(certificate, password, hash, callback) {
if (!callback && !hash && typeof password === 'function') {
callback = password
password = undefined
hash = false
} else if (!callback && hash && typeof hash === 'function') {
callback = hash
hash = false
// password will be falsy if not provided
}
// adding hash function to params, is not supported by openssl.
// process piping would be the right way (... | openssl md5)
// No idea how this can be achieved in easy with the current build in methods
// of pem.
if (hash && hash !== 'md5') {
hash = false
}
certificate = (Buffer.isBuffer(certificate) && certificate.toString()) || certificate
let type
if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) {
type = 'req'
} else if (certificate.match(/BEGIN RSA PRIVATE KEY/) || certificate.match(/BEGIN PRIVATE KEY/)) {
type = 'rsa'
} else {
type = 'x509'
}
let params = [
type,
'-noout',
'-modulus',
'-in',
'--TMPFILE--'
]
let delTempPWFiles = []
if (password) {
helper.createPasswordFile({cipher: '', password: password, passType: 'in'}, params, delTempPWFiles)
}
openssl.spawnWrapper(params, certificate, function (sslErr, code, stdout, stderr) {
function done(err) {
if (err) {
return callback(err)
}
var match = stdout.match(/Modulus=([0-9a-fA-F]+)$/m)
if (match) {
if (hash === 'md5') {
return callback(null, {
modulus: hash_md5(match[1])
})
}
return callback(null, {
modulus: match[1]
})
} else {
return callback(new Error('No modulus'))
}
}
helper.deleteTempFiles(delTempPWFiles, function (fsErr) {
done(sslErr || fsErr || stderr)
})
})
}
/**
* get the size and prime of DH parameters
* @static
* @param {String} dh parameters PEM encoded
* @param {Function} callback Callback function with an error object and {size, prime}
*/
function getDhparamInfo(dh, callback) {
dh = (Buffer.isBuffer(dh) && dh.toString()) || dh
var params = [
'dhparam',
'-text',
'-in',
'--TMPFILE--'
]
openssl.spawnWrapper(params, dh, function (err, code, stdout, stderr) {
if (err) {
return callback(err)
} else if (stderr) {
return callback(stderr)
}
var result = {}
var match = stdout.match(/Parameters: \((\d+) bit\)/)
if (match) {
result.size = Number(match[1])
}
var prime = ''
stdout.split('\n').forEach(function (line) {
if (/\s+([0-9a-f][0-9a-f]:)+[0-9a-f]?[0-9a-f]?/g.test(line)) {
prime += line.trim()
}
})
if (prime) {
result.prime = prime
}
if (!match && !prime) {
return callback(new Error('No DH info found'))
}
return callback(null, result)
})
}
/**
* config the pem module
* @static
* @param {Object} options
*/
function config(options) {
Object.keys(options).forEach(function (k) {
openssl.set(k, options[k])
})
}
/**
* Gets the fingerprint for a certificate
* @static
* @param {String} certificate PEM encoded certificate
* @param {String} [hash] hash function to use (either `md5`, `sha1` or `sha256`, defaults to `sha1`)
* @param {Function} callback Callback function with an error object and {fingerprint}
*/
function getFingerprint(certificate, hash, callback) {
if (!callback && typeof hash === 'function') {
callback = hash
hash = undefined
}
hash = hash || 'sha1'
var params = ['x509',
'-in',
'--TMPFILE--',
'-fingerprint',
'-noout',
'-' + hash
]
openssl.spawnWrapper(params, certificate, function (err, code, stdout, stderr) {
if (err) {
return callback(err)
} else if (stderr) {
return callback(stderr)
}
var match = stdout.match(/Fingerprint=([0-9a-fA-F:]+)$/m)
if (match) {
return callback(null, {
fingerprint: match[1]
})
} else {
return callback(new Error('No fingerprint'))
}
})
}
/**
* Export private key and certificate to a PKCS12 keystore
* @static
* @param {String} key PEM encoded private key
* @param {String} certificate PEM encoded certificate
* @param {String} password Password of the result PKCS12 file
* @param {Object} [options] object of cipher and optional client key password {cipher:'aes128', clientKeyPassword: 'xxxx', certFiles: ['file1','file2']}
* @param {Function} callback Callback function with an error object and {pkcs12}
*/
function createPkcs12(key, certificate, password, options, callback) {
if (!callback && typeof options === 'function') {
callback = options
options = {}
}
var params = ['pkcs12', '-export']
var delTempPWFiles = []
if (options.cipher && options.clientKeyPassword) {
// NOTICE: The password field is needed! self if it is empty.
// create password file for the import "-passin"
helper.createPasswordFile({
cipher: options.cipher,
password: options.clientKeyPassword,
passType: 'in'
}, params, delTempPWFiles)
}
// NOTICE: The password field is needed! self if it is empty.
// create password file for the password "-password"
helper.createPasswordFile({cipher: '', password: password, passType: 'word'}, params, delTempPWFiles)
params.push('-in')
params.push('--TMPFILE--')
params.push('-inkey')
params.push('--TMPFILE--')
var tmpfiles = [certificate, key]
if (options.certFiles) {
tmpfiles.push(options.certFiles.join(''))
params.push('-certfile')
params.push('--TMPFILE--')
}
openssl.execBinary(params, tmpfiles, function (sslErr, pkcs12) {
function done(err) {
if (err) {
return callback(err)
}
return callback(null, {
pkcs12: pkcs12
})
}
helper.deleteTempFiles(delTempPWFiles, function (fsErr) {
done(sslErr || fsErr)
})
})
}
/**
* read sslcert data from Pkcs12 file. Results are provided in callback response in object notation ({cert: .., ca:..., key:...})
* @static
* @param {Buffer|String} bufferOrPath Buffer or path to file
* @param {Object} [options] openssl options
* @param {Function} callback Called with error object and sslcert bundle object
*/
function readPkcs12(bufferOrPath, options, callback) {
if (!callback && typeof options === 'function') {
callback = options
options = {}
}
options.p12Password = options.p12Password || ''
var tmpfiles = []
var delTempPWFiles = []
var args = ['pkcs12', '-in', bufferOrPath]
helper.createPasswordFile({cipher: '', password: options.p12Password, passType: 'in'}, args, delTempPWFiles)
if (Buffer.isBuffer(bufferOrPath)) {
tmpfiles = [bufferOrPath]
args[2] = '--TMPFILE--'
}
if (openssl.get('Vendor') === "OPENSSL" && openssl.get('VendorVersionMajor') >= 3) {
args.push('-legacy')
args.push('-traditional')
}
if (options.clientKeyPassword) {
helper.createPasswordFile({
cipher: '',
password: options.clientKeyPassword,
passType: 'out'
}, args, delTempPWFiles)
} else {
args.push('-nodes')
}
openssl.execBinary(args, tmpfiles, function (sslErr, stdout) {
function done(err) {
var keybundle = {}
if (err && err.message.indexOf('No such file or directory') !== -1) {
err.code = 'ENOENT'
}
if (!err) {
var certs = readFromString(stdout, CERT_START, CERT_END)
keybundle.cert = certs.shift()
keybundle.ca = certs
keybundle.key = readFromString(stdout, KEY_START, KEY_END).pop()
debug("readPkcs12.execBinary - PRIVATE KEY - ?: ", keybundle.key)
if (keybundle.key) {
var args = ['rsa'];
if (openssl.get('Vendor') === "OPENSSL" && openssl.get('VendorVersionMajor') >= 3) {
args.push('-traditional')
}
args.push('-in');
args.push('--TMPFILE--');
// convert to RSA key
return openssl.exec(args, '(RSA |)PRIVATE KEY', [keybundle.key], function (err, key) {
if (err) {
debug("readPkcs12.execBinary - PRIVATE KEY convert - error: ", err)
}
//debug("readPkcs12.execBinary - PRIVATE KEY", key)
keybundle.key = key
return callback(err, keybundle)
})
}
if (options.clientKeyPassword) {
keybundle.key = readFromString(stdout, ENCRYPTED_KEY_START, ENCRYPTED_KEY_END).pop()
debug("readPkcs12.execBinary - ENCRYPTED PRIVATE KEY - ?: ", keybundle.key)
/*return openssl.exec(['rsa', '-in', '--TMPFILE--'], 'RSA PRIVATE KEY', [keybundle.key], function (err, key) {
if (err) {
debug("readPkcs12.execBinary - ENCRYPTED PRIVATE KEY - error: ", err)
}
debug("readPkcs12.execBinary - ENCRYPTED PRIVATE KEY", key)
keybundle.key = key
return callback(err, keybundle)
})*/
} else {
keybundle.key = readFromString(stdout, RSA_KEY_START, RSA_KEY_END).pop()
debug("readPkcs12.execBinary - RSA PRIVATE KEY - ?: ", keybundle.key)
/*return openssl.exec(['rsa', '-in', '--TMPFILE--'], 'RSA PRIVATE KEY', [keybundle.key], function (err, key) {
if (err) {
debug("readPkcs12.execBinary - RSA PRIVATE KEY - error: ", err)
}
debug("readPkcs12.execBinary - RSA PRIVATE KEY", key)
keybundle.key = key
return callback(err, keybundle)
})*/
}
}
return callback(err, keybundle)
}
helper.deleteTempFiles(delTempPWFiles, function (fsErr) {
done(sslErr || fsErr)
})
})
}
/**
* Check a certificate
* @static
* @param {String} certificate PEM encoded certificate
* @param {String} [passphrase] password for the certificate
* @param {Function} callback Callback function with an error object and a boolean valid
*/
function checkCertificate(certificate, passphrase, callback) {
var params
var delTempPWFiles = []
if (!callback && typeof passphrase === 'function') {
callback = passphrase
passphrase = undefined
}
certificate = (certificate || '').toString()
if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) {
params = ['req', '-text', '-noout', '-verify', '-in', '--TMPFILE--']
} else if (certificate.match(/BEGIN RSA PRIVATE KEY/) || certificate.match(/BEGIN PRIVATE KEY/)) {
params = ['rsa', '-noout', '-check', '-in', '--TMPFILE--']
} else {
params = ['x509', '-text', '-noout', '-in', '--TMPFILE--']
}
if (passphrase) {
helper.createPasswordFile({cipher: '', password: passphrase, passType: 'in'}, params, delTempPWFiles)
}
openssl.spawnWrapper(params, certificate, function (sslErr, code, stdout, stderr) {
function done(err) {
stdout = stdout && stdout.trim()
var result
switch (params[0]) {
case 'rsa':
result = /^Rsa key ok$/i.test(stdout)
break
default:
result = /Signature Algorithm/im.test(stdout)
break
}
if (!result) {
if (openssl.get('Vendor') === "OPENSSL" && openssl.get('VendorVersionMajor') >= 3) {