-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
114 lines (93 loc) · 2.18 KB
/
example_test.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package pcert
import (
"crypto/x509"
"fmt"
"log"
"os"
)
// Create a key and a self-signed certificate and save it to server.crt and server.key
func ExampleCreate_selfSigned() {
cert := NewServerCertificate("localhost")
// self-signed
certDER, key, err := CreateCertificate(cert, nil, nil)
if err != nil {
log.Fatal(err)
}
keyPEM, err := EncodeKey(key)
if err != nil {
log.Fatal(err)
}
certPEM := Encode(certDER)
err = os.WriteFile("server.crt", certPEM, 0o644)
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("server.crt", keyPEM, 0o600)
if err != nil {
log.Fatal(err)
}
}
// Load a root CA from ca.crt and ca.key and use it to create a signed server certificate
func ExampleCreate_signed() {
// load root CA
rootCACert, err := Load("ca.crt")
if err != nil {
log.Fatal(err)
}
rootCAKey, err := LoadKey("ca.key")
if err != nil {
log.Fatal(err)
}
// create signed server certificate
cert := NewServerCertificate("localhost")
certDER, key, err := CreateCertificate(cert, rootCACert, rootCAKey)
if err != nil {
log.Fatal(err)
}
keyPEM, err := EncodeKey(key)
if err != nil {
log.Fatal(err)
}
certPEM := Encode(certDER)
err = os.WriteFile("server.crt", certPEM, 0o644)
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("server.crt", keyPEM, 0o600)
if err != nil {
log.Fatal(err)
}
}
// Create a self-signed certificate with a 4096 bit RSA key
func ExampleCreateCertificateWithKeyOptions() {
cert := NewServerCertificate("localhost")
keyOptions := KeyOptions{
Algorithm: x509.RSA,
Size: 4096,
}
certDER, key, err := CreateCertificateWithKeyOptions(cert, keyOptions, nil, nil)
if err != nil {
log.Fatal(err)
}
keyPEM, err := EncodeKey(key)
if err != nil {
log.Fatal(err)
}
certPEM := Encode(certDER)
_, _ = os.Stdout.Write(certPEM)
_, _ = os.Stdout.Write(keyPEM)
}
func ExampleExtKeyUsageToString() {
cert := NewClientCertificate("myUser")
usageStr := ExtKeyUsageToString(cert.ExtKeyUsage)
fmt.Println(usageStr)
// Output:
// ClientAuth
}
func ExampleKeyUsageToString() {
cert := NewCACertificate("My Super Root CA")
usageStr := KeyUsageToString(cert.KeyUsage)
fmt.Println(usageStr)
// Output:
// CRLSign,CertSign
}