forked from eyedeekay/reseed-tools
/
utils.go
81 lines (69 loc) · 2.02 KB
/
utils.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
package reseed
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io/ioutil"
"math/big"
"net"
"path/filepath"
"strings"
"time"
)
type KeyStore struct {
Path string
}
func (ks *KeyStore) ReseederCertificate(signer []byte) (*x509.Certificate, error) {
certFile := filepath.Base(SignerFilename(string(signer)))
certString, err := ioutil.ReadFile(filepath.Join(ks.Path, "reseed", certFile))
if nil != err {
return nil, err
}
certPem, _ := pem.Decode(certString)
return x509.ParseCertificate(certPem.Bytes)
}
func SignerFilename(signer string) string {
return strings.Replace(signer, "@", "_at_", 1) + ".crt"
}
func NewTLSCertificate(host string, priv *ecdsa.PrivateKey) ([]byte, error) {
notBefore := time.Now()
notAfter := notBefore.Add(5 * 365 * 24 * time.Hour)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"I2P Anonymous Network"},
OrganizationalUnit: []string{"I2P"},
Locality: []string{"XX"},
StreetAddress: []string{"XX"},
Country: []string{"XX"},
CommonName: host,
},
NotBefore: notBefore,
NotAfter: notAfter,
SignatureAlgorithm: x509.ECDSAWithSHA512,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
}
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, err
}
return derBytes, nil
}