2021-08-22 23:55:33 +08:00
|
|
|
//go:build openssl
|
2019-05-23 01:31:11 +08:00
|
|
|
// +build openssl
|
|
|
|
|
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
|
2019-06-28 20:04:56 +08:00
|
|
|
openssl "github.com/libp2p/go-openssl"
|
2019-05-23 01:31:11 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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) {
|
2019-07-11 05:54:14 +08:00
|
|
|
if bits < MinRsaKeyBits {
|
2019-05-23 01:31:11 +08:00
|
|
|
return nil, nil, ErrRsaKeyTooSmall
|
|
|
|
}
|
|
|
|
|
|
|
|
key, err := openssl.GenerateRSAKey(bits)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2020-01-16 09:29:26 +08:00
|
|
|
return &RsaPrivateKey{opensslPrivateKey{key}}, &RsaPublicKey{opensslPublicKey{key: key}}, nil
|
2019-05-23 01:31:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetPublic returns a public key
|
|
|
|
func (sk *RsaPrivateKey) GetPublic() PubKey {
|
2020-01-16 09:29:26 +08:00
|
|
|
return &RsaPublicKey{opensslPublicKey{key: sk.opensslPrivateKey.key}}
|
2019-05-23 01:31:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
2019-10-22 06:52:27 +08:00
|
|
|
if 8*key.key.Size() < MinRsaKeyBits {
|
|
|
|
return nil, ErrRsaKeyTooSmall
|
|
|
|
}
|
2019-05-23 01:31:11 +08:00
|
|
|
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
|
|
|
|
}
|
2019-10-22 06:52:27 +08:00
|
|
|
if 8*key.key.Size() < MinRsaKeyBits {
|
|
|
|
return nil, ErrRsaKeyTooSmall
|
|
|
|
}
|
2019-05-23 01:31:11 +08:00
|
|
|
if key.Type() != RSA {
|
|
|
|
return nil, errors.New("not actually an rsa public key")
|
|
|
|
}
|
|
|
|
return &RsaPublicKey{key}, nil
|
|
|
|
}
|