/
cert.go
53 lines (47 loc) · 1.22 KB
/
cert.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
package awsiotdevice
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
)
// certificateRequestData 証明書要求データ
type certificateRequestData struct {
// 秘密鍵
privateKey string
// CSR
csr string
}
func createCsr(curve elliptic.Curve, signatureAlgorithm x509.SignatureAlgorithm) (*certificateRequestData, error) {
// generate Private Key
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, err
}
// create CSR
csrTemplate := x509.CertificateRequest{
Subject: pkix.Name{CommonName: "AWS IoT Certificate"},
SignatureAlgorithm: signatureAlgorithm,
}
csrCertificate, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, privateKey)
if err != nil {
return nil, err
}
csr := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST", Bytes: csrCertificate,
})
// serialize key and CSR
privateKeyBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return nil, err
}
privateKeyPem := pem.EncodeToMemory(&pem.Block{
Type: "ECDH PRIVATE KEY", Bytes: privateKeyBytes,
})
return &certificateRequestData{
privateKey: string(privateKeyPem),
csr: string(csr),
}, nil
}