-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathgenkeycert.js
executable file
·81 lines (73 loc) · 2.06 KB
/
genkeycert.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
#!/usr/bin/env node
// © Copyright IBM Corporation 2016,2017.
// Node module: microgateway
// LICENSE: Apache 2.0, https://www.apache.org/licenses/LICENSE-2.0
'use strict';
var pem = require('pem');
var fs = require('fs');
var path = require('path');
var keyPath = path.resolve(__dirname, '../config/key.pem');
var certPath = path.resolve(__dirname, '../config/cert.pem');
function checkServiceKey(cb) {
try {
fs.statSync(keyPath);
var serviceKey = fs.readFileSync(keyPath);
cb(null, serviceKey);
} catch (e) {
if (e.code === 'ENOENT') {
// if key.pem not exist, generate the private key
console.log("Create the service key 'config/key.pem'");
pem.createPrivateKey(2048, function(e, keyData) {
if (e) {
cb(e);
} else {
fs.writeFile(keyPath, keyData.key, function(e) {
cb(e, e || { newKey: true, keyData: keyData.key });
});
}
});
} else {
cb(e);
}
}
}
function createCertificate(keyData, cb) {
pem.createCertificate({ serviceKey: keyData }, function(e, certResult) {
if (e) {
cb(e);
} else {
fs.writeFile(certPath, certResult.certificate, cb);
}
});
}
function createCertificateCB(err) {
if (err) {
console.log("Error when creating the cert file 'config/cert.pem': " + err);
process.exit(1);
}
}
checkServiceKey(function(err, result) {
if (err) {
console.log("Error when checking/creating the service key file 'config/key.pem': " + err);
process.exit(1);
}
var certFileExist = false;
try {
fs.statSync(certPath);
certFileExist = true;
} catch (e) {
if (e.code !== 'ENOENT') {
console.log("Error when checking the cert file 'config/cert.pem': " + e);
process.exit(1);
}
}
if (certFileExist) {
if (result.newKey) {
console.log("Recreate the cert file 'config/cert.pem'");
createCertificate(result.keyData, createCertificateCB);
}
} else {
console.log("Create the cert file 'config/cert.pem'");
createCertificate(result.keyData, createCertificateCB);
}
});