gitee.com/lh-her-team/common@v1.5.1/helper/libp2pcrypto/rsa_openssl.go (about)

     1  // +build openssl
     2  
     3  package libp2pcrypto
     4  
     5  import (
     6  	"errors"
     7  	"io"
     8  
     9  	openssl "github.com/libp2p/go-openssl"
    10  )
    11  
    12  // RsaPrivateKey is an rsa private key
    13  type RsaPrivateKey struct {
    14  	opensslPrivateKey
    15  }
    16  
    17  // RsaPublicKey is an rsa public key
    18  type RsaPublicKey struct {
    19  	opensslPublicKey
    20  }
    21  
    22  // GenerateRSAKeyPair generates a new rsa private and public key
    23  func GenerateRSAKeyPair(bits int, _ io.Reader) (PrivKey, PubKey, error) {
    24  	if bits < MinRsaKeyBits {
    25  		return nil, nil, ErrRsaKeyTooSmall
    26  	}
    27  	key, err := openssl.GenerateRSAKey(bits)
    28  	if err != nil {
    29  		return nil, nil, err
    30  	}
    31  	return &RsaPrivateKey{opensslPrivateKey{key}}, &RsaPublicKey{opensslPublicKey{key: key}}, nil
    32  }
    33  
    34  // GetPublic returns a public key
    35  func (sk *RsaPrivateKey) GetPublic() PubKey {
    36  	return &RsaPublicKey{opensslPublicKey{key: sk.opensslPrivateKey.key}}
    37  }
    38  
    39  // UnmarshalRsaPrivateKey returns a private key from the input x509 bytes
    40  func UnmarshalRsaPrivateKey(b []byte) (PrivKey, error) {
    41  	key, err := unmarshalOpensslPrivateKey(b)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	if 8*key.key.Size() < MinRsaKeyBits {
    46  		return nil, ErrRsaKeyTooSmall
    47  	}
    48  	if key.Type() != RSA {
    49  		return nil, errors.New("not actually an rsa public key")
    50  	}
    51  	return &RsaPrivateKey{key}, nil
    52  }
    53  
    54  // UnmarshalRsaPublicKey returns a public key from the input x509 bytes
    55  func UnmarshalRsaPublicKey(b []byte) (PubKey, error) {
    56  	key, err := unmarshalOpensslPublicKey(b)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  	if 8*key.key.Size() < MinRsaKeyBits {
    61  		return nil, ErrRsaKeyTooSmall
    62  	}
    63  	if key.Type() != RSA {
    64  		return nil, errors.New("not actually an rsa public key")
    65  	}
    66  	return &RsaPublicKey{key}, nil
    67  }