From 710e01de4ded6fd333eeb8ec6a5379b45f0884c6 Mon Sep 17 00:00:00 2001 From: Mr-houzi <26339918+Mr-houzi@users.noreply.github.com> Date: Thu, 24 Mar 2022 14:22:06 +0800 Subject: [PATCH] =?UTF-8?q?fix=EF=BC=9Arsa=20invalid=20key=20result=20in?= =?UTF-8?q?=20panic=20nil=20pointer=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jon --- rsa.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/rsa.go b/rsa.go index 0687ba2..151994e 100644 --- a/rsa.go +++ b/rsa.go @@ -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 { @@ -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 { @@ -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 { @@ -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 { @@ -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 {