阅读背景:

golang Rsa_weixin_30672019的博客

来源:互联网 
package models                                                                                                                                                               

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

func RsaDecrypt(ciphertext []byte, pri_key []byte) ([]byte, error) {

    block, _ := pem.Decode(pri_key)
    if block == nil {
        return nil, errors.New("invalid rsa private key")
    }   

    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err 
    }   

    return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

func RsaEncrypt(plaintext []byte, pub_key []byte) ([]byte, error) {

    block, _ := pem.Decode(pub_key)
    if block == nil {
        return nil, errors.New("invalid rsa public key")
    }   

    pubInf, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err 
    }   
    pub := pubInf.(*rsa.PublicKey)
    return rsa.EncryptPKCS1v15(rand.Reader, pub, plaintext)
}
package models                        



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: