Debian Codegraph @

keys/rsa/rsa.go

raw
1 //package Rsa provides helpers for creating rsa leys
2 package Rsa
3
4 import (
5 "crypto/rsa"
6 "crypto/x509"
7 "encoding/pem"
8 "errors"
9 )
10
11 // ReadPrivate loads rsa.PrivateKey from PKCS1 or PKCS8 blobs
12 func ReadPrivate(raw []byte) (key *rsa.PrivateKey,err error) {
13 var encoded *pem.Block
14
15 if encoded, _ = pem.Decode(raw); encoded == nil {
16 return nil, errors.New("Rsa.NewPrivate(): Key must be PEM encoded PKCS1 or PKCS8 private key")
17 }
18
19 var parsedKey interface{}
20
21 if parsedKey,err=x509.ParsePKCS1PrivateKey(encoded.Bytes);err!=nil {
22 if parsedKey, err = x509.ParsePKCS8PrivateKey(encoded.Bytes);err!=nil {
23 return nil,err
24 }
25 }
26
27 var ok bool
28
29 if key,ok=parsedKey.(*rsa.PrivateKey);!ok {
30 return nil, errors.New("Rsa.NewPrivate(): Key is not valid *rsa.PrivateKey")
31 }
32
33 return key,nil
34 }
35
36 // ReadPublic loads rsa.PublicKey from PKIX or PKCS1 X509 blobs
37 func ReadPublic(raw []byte) (key *rsa.PublicKey,err error) {
38 var encoded *pem.Block
39
40 if encoded, _ = pem.Decode(raw); encoded == nil {
41 return nil, errors.New("Rsa.NewPublic(): Key must be PEM encoded PKCS1 X509 certificate or PKIX public key")
42 }
43
44 var parsedKey interface{}
45 var cert *x509.Certificate
46
47 if parsedKey, err = x509.ParsePKIXPublicKey(encoded.Bytes); err != nil {
48 if cert,err = x509.ParseCertificate(encoded.Bytes);err!=nil {
49 return nil, err
50 }
51
52 parsedKey=cert.PublicKey
53 }
54
55 var ok bool
56
57 if key, ok = parsedKey.(*rsa.PublicKey); !ok {
58 return nil, errors.New("Rsa.NewPublic(): Key is not a valid RSA public key")
59 }
60
61 return key, nil
62 }