github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/crypto_rsa.go (about)

     1  package f
     2  
     3  import (
     4  	"crypto"
     5  	"crypto/rand"
     6  	"crypto/rsa"
     7  	"crypto/x509"
     8  	"encoding/pem"
     9  )
    10  
    11  // RSAPublicKey 公钥加密或验签.
    12  type RSAPublicKey struct {
    13  	*rsa.PublicKey
    14  }
    15  
    16  // NewRSAPublicKey get a RSA Public Key Encrypt.
    17  func NewRSAPublicKey(publicKeyPemBytes []byte) *RSAPublicKey {
    18  	block, _ := pem.Decode(publicKeyPemBytes)
    19  	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
    20  	Must(err)
    21  	key := publicKey.(*rsa.PublicKey)
    22  	return &RSAPublicKey{PublicKey: key}
    23  }
    24  
    25  // EncryptPKCS1v15 encrypts the given message with RSA and the padding
    26  // scheme from PKCS#1 v1.5.  The message must be no longer than the
    27  // length of the public modulus minus 11 bytes.
    28  func (e *RSAPublicKey) EncryptPKCS1v15(origData []byte) ([]byte, error) {
    29  	return rsa.EncryptPKCS1v15(rand.Reader, e.PublicKey, origData)
    30  }
    31  
    32  // VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature.
    33  // err := VerifyPKCS1v15(origData, sig, crypto.SHA256)
    34  // err := VerifyPKCS1v15(origData, sig, crypto.SHA384)
    35  // err := VerifyPKCS1v15(origData, sig, crypto.SHA512)
    36  func (e *RSAPublicKey) VerifyPKCS1v15(origData, sig []byte, hash crypto.Hash) error {
    37  	hasher := hash.New()
    38  	hasher.Write(origData)
    39  	return rsa.VerifyPKCS1v15(e.PublicKey, hash, hasher.Sum(nil), sig)
    40  }
    41  
    42  // RSAPrivateKey 私钥解密或签名.
    43  type RSAPrivateKey struct {
    44  	*rsa.PrivateKey
    45  }
    46  
    47  // NewRSAPrivateKey get a RSA Private Key Decrypt.
    48  func NewRSAPrivateKey(privateKeyPemBytes []byte) *RSAPrivateKey {
    49  	block, _ := pem.Decode(privateKeyPemBytes)
    50  	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    51  	Must(err)
    52  	return &RSAPrivateKey{PrivateKey: privateKey}
    53  }
    54  
    55  // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
    56  // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
    57  func (e *RSAPrivateKey) DecryptPKCS1v15(encrypted []byte) ([]byte, error) {
    58  	return rsa.DecryptPKCS1v15(rand.Reader, e.PrivateKey, encrypted)
    59  }
    60  
    61  // SignPKCS1v15 calculates the signature of hashed using RSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5.
    62  // sig, err := SignPKCS1v15(origData, crypto.SHA256)
    63  // sig, err := SignPKCS1v15(origData, crypto.SHA384)
    64  // sig, err := SignPKCS1v15(origData, crypto.SHA512)
    65  func (e *RSAPrivateKey) SignPKCS1v15(origData []byte, hash crypto.Hash) ([]byte, error) {
    66  	hasher := hash.New()
    67  	hasher.Write(origData)
    68  	return rsa.SignPKCS1v15(rand.Reader, e.PrivateKey, hash, hasher.Sum(nil))
    69  }