This repository has been archived by the owner on Nov 14, 2023. It is now read-only.
/
selfsigned.go
90 lines (79 loc) · 2.53 KB
/
selfsigned.go
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
package goauth
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"log"
"math/big"
"net"
"time"
)
// Generate self-signed certs for debugging purposes
func genRSAKey() *rsa.PrivateKey {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatalf("failed to generate private key: %v", err)
}
return privateKey
}
func certificateTemplate() x509.Certificate {
return x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: "localhost",
Organization: []string{"gohttp-testing"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0), // Valid for 1 year
BasicConstraintsValid: true,
IsCA: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("0.0.0.0")},
}
}
func dnsCertificateTemplate(commonName string, dnsName []string) x509.Certificate {
return x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"gohttp-testing"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0), // Valid for 1 year
BasicConstraintsValid: true,
IsCA: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
//IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
DNSNames: dnsName,
PermittedDNSDomains: dnsName,
PermittedDNSDomainsCritical: true,
}
}
func CreateCertificate() tls.Certificate {
privateKey := genRSAKey()
template := certificateTemplate()
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privateKey.Public(), privateKey)
if err != nil {
log.Fatalf("could not parse certificate : %s", err)
}
return tls.Certificate{
Certificate: [][]byte{certBytes},
PrivateKey: privateKey,
}
}
func CreateDnsCertificate(commonName string, dnsName []string) tls.Certificate {
privateKey := genRSAKey()
template := dnsCertificateTemplate(commonName, dnsName)
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privateKey.Public(), privateKey)
if err != nil {
log.Fatalf("could not parse certificate : %s", err)
}
return tls.Certificate{
Certificate: [][]byte{certBytes},
PrivateKey: privateKey,
}
}