网上关于rsa的用法很多,尤其是 https://cloud.tencent.com/developer/section/1140761,但是上面的例子不全面
package utils
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"os"
)
func RSAEncryptOAEP(publicKeypem, labeltext, plaintext string) (ciphertext string) {
publicBlock, _ := pem.Decode([]byte(publicKeypem))
if publicBlock == nil {
panic("public key error")
}
pub, err := x509.ParsePKIXPublicKey(publicBlock.Bytes)
if err != nil {
panic("publicKey is not *rsa.PublicKey")
}
publicKey := pub.(*rsa.PublicKey)
rng := rand.Reader
secretMessage := []byte(plaintext)
label := []byte(labeltext)
cipherbyte, err := rsa.EncryptOAEP(sha256.New(), rng, publicKey, secretMessage, label)
if err != nil {
panic(fmt.Sprintf("Error from encryption: %s\n", err))
}
// 由于加密是随机函数,密文将是
// 每次都不一样。
//fmt.Printf("Ciphertext: %x\n", cipherbyte)
ciphertext = fmt.Sprintf("%x\n", cipherbyte)
return
}
func RSADecryptOAEP(privateKeypem, labeltext, ciphertext string) (plaintext string) {
privateBlock, _ := pem.Decode([]byte(privateKeypem))
if privateBlock == nil {
panic("private key error")
}
privateKey, err := x509.ParsePKCS1PrivateKey(privateBlock.Bytes)
if err != nil {
panic("privateKey is not *rsa.PrivateKey")
}
/*
prkI, err := x509.ParsePKCS8PrivateKey(privateBlock.Bytes)
if err != nil {
panic("privateKey is not *rsa.PrivateKey")
}
privateKey := prkI.(*rsa.PrivateKey)
*/
rng := rand.Reader
///
cipherByte, _ := hex.DecodeString(ciphertext)
label := []byte(labeltext)
plainbyte, err := rsa.DecryptOAEP(sha256.New(), rng, privateKey, cipherByte, la