package utils

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "errors"
)

// 加密
func RsaEncrypt(origData []byte, publicKey []byte) ([]byte, error) {
    //解密pem格式的公钥
    block, _ := pem.Decode(publicKey)
    if block == nil {
        return nil, errors.New("公钥错误")
    }
    // 解析公钥
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    // 类型断言
    pub := pubInterface.(*rsa.PublicKey)
    //加密
    return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// 解密
func RsaDecrypt(ciphertext []byte, privateKey []byte) ([]byte, error) {
    //解密
    p, _ := pem.Decode(privateKey)
    if p == nil {
        return nil, errors.New("私钥错误")
    }
    key, err := x509.ParsePKCS8PrivateKey(p.Bytes)
    if err != nil {
        return nil, err
    }
    i := key.(*rsa.PrivateKey)
    // 解密
    return rsa.DecryptPKCS1v15(rand.Reader, i, ciphertext)
}