1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| func RsaEncrypt(plainText, publicKey string) (string, error) { block, _ := pem.Decode([]byte(publicKey)) pubKey, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return "", err }
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), []byte(plainText)) if err != nil { return "", err }
return base64.StdEncoding.EncodeToString(cipherText), nil }
func RsaDecrypt(cipherText, privateKey string) (string, error) { block, _ := pem.Decode([]byte(privateKey)) priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return "", err }
cipherTextData, err := base64.StdEncoding.DecodeString(cipherText) if err != nil { return "", err }
plainTextData, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, cipherTextData) if err != nil { return "", err }
return string(plainTextData), nil }
|