04.rsa v2 - wwj-2017-1117/AES_OK GitHub Wiki
package main
import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" )
//RSA 非对称性加密 //公钥加密、私钥解密
//1. 声明私钥 , 自己保留
var priKey = []byte(
)
//2. 声明公钥 ,公钥可以公开给所有人使用,可以用作加密,可以用作验签 var pubKey = []byte(``)
//RSA加密算法 func RSAEncrypt2(origData []byte) []byte { //通过公钥加密 block, _ := pem.Decode(pubKey) //解析公钥 pubInterface, _ := x509.ParsePKIXPublicKey(block.Bytes)
//加载公钥
pub := pubInterface.(*rsa.PublicKey)
//利用公钥pub加密
bits, _ := rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
//返回密文
return bits
}
//RSA解密算法 func RSADecrypt2(cipherTxt []byte) []byte { //通过私钥解密 block, _ := pem.Decode(priKey) //解析私钥 pri, _ := x509.ParsePKCS1PrivateKey(block.Bytes) //解密 bits, _ := rsa.DecryptPKCS1v15(rand.Reader, pri, cipherTxt) //返回明文 return bits }
func main() { //加密 cipher := RSAEncrypt2([]byte("hello BBC")) fmt.Println(cipher)
//解密
plain := RSADecrypt2(cipher)
fmt.Println("解密后数据:" + string(plain))
}