Skip to content

Commit

Permalink
fix:rsa invalid key result in panic nil pointer (#18) (#19)
Browse files Browse the repository at this point in the history
Co-authored-by: Jon <techlee@qq.com>

Co-authored-by: Mr-houzi <26339918+Mr-houzi@users.noreply.github.com>
  • Loading branch information
leeqvip and Mr-houzi authored Mar 24, 2022
1 parent e5bd081 commit 3f7d73c
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ func RSAGenerateKey(bits int, out io.Writer) error {
// RSAGeneratePublicKey generate RSA public key
func RSAGeneratePublicKey(priKey []byte, out io.Writer) error {
block, _ := pem.Decode(priKey)
if block == nil{
return errors.New("key is invalid format")
}

// x509 parse
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
Expand All @@ -47,6 +51,10 @@ func RSAGeneratePublicKey(priKey []byte, out io.Writer) error {
// RSAEncrypt RSA encrypt
func RSAEncrypt(src, pubKey []byte) ([]byte, error) {
block, _ := pem.Decode(pubKey)
if block == nil{
return nil, errors.New("key is invalid format")
}

// x509 parse
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
Expand All @@ -69,6 +77,10 @@ func RSAEncrypt(src, pubKey []byte) ([]byte, error) {
// RSADecrypt RSA decrypt
func RSADecrypt(src, priKey []byte) ([]byte, error) {
block, _ := pem.Decode(priKey)
if block == nil{
return nil, errors.New("key is invalid format")
}

// x509 parse
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
Expand All @@ -86,6 +98,10 @@ func RSADecrypt(src, priKey []byte) ([]byte, error) {
// RSASign RSA sign, use crypto.SHA256
func RSASign(src []byte, priKey []byte) ([]byte, error) {
block, _ := pem.Decode(priKey)
if block == nil{
return nil, errors.New("key is invalid format")
}

// x509 parse
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
Expand All @@ -110,6 +126,10 @@ func RSASign(src []byte, priKey []byte) ([]byte, error) {
// RSAVerify RSA Verify
func RSAVerify(src, sign, pubKey []byte) error {
block, _ := pem.Decode(pubKey)
if block == nil{
return errors.New("key is invalid format")
}

// x509 parse
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
Expand Down

0 comments on commit 3f7d73c

Please sign in to comment.