-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rsa_openssl.go
69 lines (59 loc) · 1.61 KB
/
rsa_openssl.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
//go:build openssl
// +build openssl
package crypto
import (
"errors"
"io"
openssl "github.com/libp2p/go-openssl"
)
// RsaPrivateKey is an rsa private key
type RsaPrivateKey struct {
opensslPrivateKey
}
// RsaPublicKey is an rsa public key
type RsaPublicKey struct {
opensslPublicKey
}
// GenerateRSAKeyPair generates a new rsa private and public key
func GenerateRSAKeyPair(bits int, _ io.Reader) (PrivKey, PubKey, error) {
if bits < MinRsaKeyBits {
return nil, nil, ErrRsaKeyTooSmall
}
key, err := openssl.GenerateRSAKey(bits)
if err != nil {
return nil, nil, err
}
return &RsaPrivateKey{opensslPrivateKey{key}}, &RsaPublicKey{opensslPublicKey{key: key}}, nil
}
// GetPublic returns a public key
func (sk *RsaPrivateKey) GetPublic() PubKey {
return &RsaPublicKey{opensslPublicKey{key: sk.opensslPrivateKey.key}}
}
// UnmarshalRsaPrivateKey returns a private key from the input x509 bytes
func UnmarshalRsaPrivateKey(b []byte) (PrivKey, error) {
key, err := unmarshalOpensslPrivateKey(b)
if err != nil {
return nil, err
}
if 8*key.key.Size() < MinRsaKeyBits {
return nil, ErrRsaKeyTooSmall
}
if key.Type() != RSA {
return nil, errors.New("not actually an rsa public key")
}
return &RsaPrivateKey{key}, nil
}
// UnmarshalRsaPublicKey returns a public key from the input x509 bytes
func UnmarshalRsaPublicKey(b []byte) (PubKey, error) {
key, err := unmarshalOpensslPublicKey(b)
if err != nil {
return nil, err
}
if 8*key.key.Size() < MinRsaKeyBits {
return nil, ErrRsaKeyTooSmall
}
if key.Type() != RSA {
return nil, errors.New("not actually an rsa public key")
}
return &RsaPublicKey{key}, nil
}