forked from aws/aws-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
privkey.go
68 lines (57 loc) · 1.63 KB
/
privkey.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
package sign
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
)
// LoadPEMPrivKeyFile reads a PEM encoded RSA private key from the file name.
// A new RSA private key will be returned if no error.
func LoadPEMPrivKeyFile(name string) (*rsa.PrivateKey, error) {
file, err := os.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
return LoadPEMPrivKey(file)
}
// LoadPEMPrivKey reads a PEM encoded RSA private key from the io.Reader.
// A new RSA private key will be returned if no error.
func LoadPEMPrivKey(reader io.Reader) (*rsa.PrivateKey, error) {
block, err := loadPem(reader)
if err != nil {
return nil, err
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
// LoadEncryptedPEMPrivKey decrypts the PEM encoded private key using the
// password provided returning a RSA private key. If the PEM data is invalid,
// or unable to decrypt an error will be returned.
func LoadEncryptedPEMPrivKey(reader io.Reader, password []byte) (*rsa.PrivateKey, error) {
block, err := loadPem(reader)
if err != nil {
return nil, err
}
decryptedBlock, err := x509.DecryptPEMBlock(block, password)
if err != nil {
return nil, err
}
return x509.ParsePKCS1PrivateKey(decryptedBlock)
}
func loadPem(reader io.Reader) (*pem.Block, error) {
b, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
block, _ := pem.Decode(b)
if block == nil {
// pem.Decode will set block to nil if there is no PEM data in the input
// the second parameter will contain the provided bytes that failed
// to be decoded.
return nil, fmt.Errorf("no valid PEM data provided")
}
return block, nil
}