-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcryptography.go
76 lines (62 loc) · 1.6 KB
/
cryptography.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
package gutil
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
type KeyFormat int
const (
KeyFormatPKCS1 = 1
KeyFormatPKCS8 = 2
KeyFormatPKIX = 3
)
// ParsePrivateKeyFromPem parses private key from the pem value.
func ParseRSAPrivateKey(pemBytes []byte, keyFormat KeyFormat) (*rsa.PrivateKey, error) {
key, err := ParsePrivateKey(pemBytes, keyFormat)
if err != nil {
return nil, err
}
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("key type is not RSA")
}
return rsaKey, nil
}
func ParsePrivateKey(pemBytes []byte, keyFormat KeyFormat) (key interface{}, err error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
switch keyFormat {
case KeyFormatPKCS1:
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
case KeyFormatPKCS8:
key, err = x509.ParsePKCS8PrivateKey(block.Bytes)
}
return
}
func ParseRSAPublicKey(pemBytes []byte, format KeyFormat) (*rsa.PublicKey, error) {
pub, err := ParsePublicKey(pemBytes, format)
if err != nil {
return nil, err
}
publicKey, ok := pub.(*rsa.PublicKey)
if !ok {
return nil, errors.New("key type is not RSA")
}
return publicKey, nil
}
func ParsePublicKey(pemBytes []byte, keyFormat KeyFormat) (key interface{}, err error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
switch keyFormat {
case KeyFormatPKCS1:
key, err = x509.ParsePKCS1PublicKey(block.Bytes)
case KeyFormatPKCS8:
key, err = x509.ParsePKIXPublicKey(block.Bytes)
}
return
}