-
Notifications
You must be signed in to change notification settings - Fork 0
/
pem.go
67 lines (58 loc) · 1.48 KB
/
pem.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
package pem
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
func GenerateRsaKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey) {
privateKey, _ := rsa.GenerateKey(rand.Reader, bits)
return privateKey, &privateKey.PublicKey
}
func ExportRsaPrivateKeyAsPemStr(privateKey *rsa.PrivateKey) string {
privatePem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
},
)
return string(privatePem)
}
func ParseRsaPrivateKeyFromPemStr(privatePem string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(privatePem))
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
func ExportRsaPublicKeyAsPemStr(pubkey *rsa.PublicKey) (string, error) {
b, err := x509.MarshalPKIXPublicKey(pubkey)
if err != nil {
return "", err
}
publicPem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: b,
},
)
return string(publicPem), nil
}
func ParseRsaPublicKeyFromPemStr(publicPem string) (*rsa.PublicKey, error) {
block, _ := pem.Decode([]byte(publicPem))
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
switch pub := pub.(type) {
case *rsa.PublicKey:
return pub, nil
default:
break // fall through
}
return nil, errors.New("Key type is not RSA")
}