Projekt

Obecné

Profil

Stáhnout (5.48 KB) Statistiky
| Větev: | Revize:
1
var forge = require('node-forge');
2

    
3
// a hexString is considered negative if it's most significant bit is 1
4
// because serial numbers use ones' complement notation
5
// this RFC in section 4.1.2.2 requires serial numbers to be positive
6
// http://www.ietf.org/rfc/rfc5280.txt
7
function toPositiveHex(hexString){
8
  var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);
9
  if (mostSiginficativeHexAsInt < 8){
10
    return hexString;
11
  }
12

    
13
  mostSiginficativeHexAsInt -= 8;
14
  return mostSiginficativeHexAsInt.toString() + hexString.substring(1);
15
}
16

    
17
function getAlgorithm(key) {
18
  switch (key) {
19
    case 'sha256':
20
      return forge.md.sha256.create();
21
    default:
22
      return forge.md.sha1.create();
23
  }
24
}
25

    
26
exports.generate = function generate(attrs, options, done) {
27
  if (typeof attrs === 'function') {
28
    done = attrs;
29
    attrs = undefined;
30
  } else if (typeof options === 'function') {
31
    done = options;
32
    options = {};
33
  }
34

    
35
  options = options || {};
36

    
37
  var generatePem = function (keyPair) {
38
    var cert = forge.pki.createCertificate();
39

    
40
    cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)
41

    
42
    cert.validity.notBefore = new Date();
43
    cert.validity.notAfter = new Date();
44
    cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365));
45

    
46
    attrs = attrs || [{
47
      name: 'commonName',
48
      value: 'example.org'
49
    }, {
50
      name: 'countryName',
51
      value: 'US'
52
    }, {
53
      shortName: 'ST',
54
      value: 'Virginia'
55
    }, {
56
      name: 'localityName',
57
      value: 'Blacksburg'
58
    }, {
59
      name: 'organizationName',
60
      value: 'Test'
61
    }, {
62
      shortName: 'OU',
63
      value: 'Test'
64
    }];
65

    
66
    cert.setSubject(attrs);
67
    cert.setIssuer(attrs);
68

    
69
    cert.publicKey = keyPair.publicKey;
70

    
71
    cert.setExtensions(options.extensions || [{
72
      name: 'basicConstraints',
73
      cA: true
74
    }, {
75
      name: 'keyUsage',
76
      keyCertSign: true,
77
      digitalSignature: true,
78
      nonRepudiation: true,
79
      keyEncipherment: true,
80
      dataEncipherment: true
81
    }, {
82
      name: 'subjectAltName',
83
      altNames: [{
84
        type: 6, // URI
85
        value: 'http://example.org/webid#me'
86
      }]
87
    }]);
88

    
89
    cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));
90

    
91
    const fingerprint = forge.md.sha1
92
                          .create()
93
                          .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())
94
                          .digest()
95
                          .toHex()
96
                          .match(/.{2}/g)
97
                          .join(':');
98

    
99
    var pem = {
100
      private:     forge.pki.privateKeyToPem(keyPair.privateKey),
101
      public:      forge.pki.publicKeyToPem(keyPair.publicKey),
102
      cert:        forge.pki.certificateToPem(cert),
103
      fingerprint: fingerprint,
104
    };
105

    
106
    if (options && options.pkcs7) {
107
      var p7 = forge.pkcs7.createSignedData();
108
      p7.addCertificate(cert);
109
      pem.pkcs7 = forge.pkcs7.messageToPem(p7);
110
    }
111

    
112
    if (options && options.clientCertificate) {
113
      var clientkeys = forge.pki.rsa.generateKeyPair(1024);
114
      var clientcert = forge.pki.createCertificate();
115
      clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));
116
      clientcert.validity.notBefore = new Date();
117
      clientcert.validity.notAfter = new Date();
118
      clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);
119

    
120
      var clientAttrs = JSON.parse(JSON.stringify(attrs));
121

    
122
      for(var i = 0; i < clientAttrs.length; i++) {
123
        if(clientAttrs[i].name === 'commonName') {
124
          if( options.clientCertificateCN )
125
            clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };
126
          else
127
            clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };
128
        }
129
      }
130

    
131
      clientcert.setSubject(clientAttrs);
132

    
133
      // Set the issuer to the parent key
134
      clientcert.setIssuer(attrs);
135

    
136
      clientcert.publicKey = clientkeys.publicKey;
137

    
138
      // Sign client cert with root cert
139
      clientcert.sign(keyPair.privateKey);
140

    
141
      pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);
142
      pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);
143
      pem.clientcert = forge.pki.certificateToPem(clientcert);
144

    
145
      if (options.pkcs7) {
146
        var clientp7 = forge.pkcs7.createSignedData();
147
        clientp7.addCertificate(clientcert);
148
        pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);
149
      }
150
    }
151

    
152
    var caStore = forge.pki.createCaStore();
153
    caStore.addCertificate(cert);
154

    
155
    try {
156
      forge.pki.verifyCertificateChain(caStore, [cert],
157
        function (vfd, depth, chain) {
158
          if (vfd !== true) {
159
            throw new Error('Certificate could not be verified.');
160
          }
161
          return true;
162
        });
163
    }
164
    catch(ex) {
165
      throw new Error(ex);
166
    }
167

    
168
    return pem;
169
  };
170

    
171
  var keySize = options.keySize || 1024;
172

    
173
  if (done) { // async scenario
174
    return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {
175
      if (err) { return done(err); }
176

    
177
      try {
178
        return done(null, generatePem(keyPair));
179
      } catch (ex) {
180
        return done(ex);
181
      }
182
    });
183
  }
184

    
185
  var keyPair = options.keyPair ? {
186
    privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),
187
    publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)
188
  } : forge.pki.rsa.generateKeyPair(keySize);
189

    
190
  return generatePem(keyPair);
191
};
(5-5/6)