-
Notifications
You must be signed in to change notification settings - Fork 2
/
selfsigned.js
60 lines (56 loc) · 1.74 KB
/
selfsigned.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
import forge from 'node-forge'
import fs from 'fs'
import path from 'path'
export const createRsaCert = ({ attrs, extensions }) => {
// generate cert
const pki = forge.pki
const keypair = pki.rsa.generateKeyPair(4096)
const cert = pki.createCertificate()
cert.publicKey = keypair.publicKey
cert.serialNumber = '01'
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 100)
if (!attrs) throw TypeError('attrs is required')
cert.setSubject(attrs)
cert.setIssuer(attrs)
if (extensions) cert.setExtensions(extensions)
cert.sign(keypair.privateKey, forge.md.sha256.create())
return {
cert: pki.certificateToPem(cert),
key: pki.privateKeyToPem(keypair.privateKey),
}
}
export const getCertOrCreate = () => {
const CERTIFICATE_FILE = './.certificate.json'
if (fs.existsSync(path.join(__dirname, CERTIFICATE_FILE))) return require(CERTIFICATE_FILE)
const cert = createRsaCert({
attrs: [
{ shortName: 'CN', value: 'localhost' },
{ shortName: 'C', value: 'TW' },
{ shortName: 'ST', value: 'Taipei' },
{ shortName: 'L', value: 'Taipei' },
{ shortName: 'O', value: 'Test' },
{ shortName: 'OU', value: 'Test' },
],
extensions: [
{ name: 'basicConstraints', cA: true },
{
cRLSign: true,
dataEncipherment: true,
digitalSignature: true,
keyCertSign: true,
keyEncipherment: true,
name: 'keyUsage',
nonRepudiation: true,
},
{
name: 'subjectAltName',
altNames: [
{ type: 2, value: 'localhost' },
{ type: 7, ip: '127.0.0.1' },
],
},
],
})
fs.writeFileSync(path.join(__dirname, CERTIFICATE_FILE), JSON.stringify(cert, null, 2))
return cert
}