github.com/tickstep/library-go@v0.1.1/crypto/rsa.go (about) 1 package crypto 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "crypto/x509" 7 "encoding/pem" 8 "errors" 9 ) 10 11 // 加密 12 func RsaEncrypt(publicKey, origData []byte) ([]byte, error) { 13 //解密pem格式的公钥 14 block, _ := pem.Decode(publicKey) 15 if block == nil { 16 return nil, errors.New("public key error") 17 } 18 // 解析公钥 19 pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) 20 if err != nil { 21 return nil, err 22 } 23 // 类型断言 24 pub := pubInterface.(*rsa.PublicKey) 25 //加密 26 return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) 27 } 28 29 // 解密 30 func RsaDecrypt(privateKey, ciphertext []byte) ([]byte, error) { 31 //解密 32 block, _ := pem.Decode(privateKey) 33 if block == nil { 34 return nil, errors.New("private key error!") 35 } 36 //解析PKCS1格式的私钥 37 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) 38 if err != nil { 39 return nil, err 40 } 41 // 解密 42 return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) 43 }