golang Rsa

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)
}

  

posted @ 2016-08-11 22:01  hao.ma  阅读(419)  评论(0编辑  收藏  举报