package util import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" ) // EncryptWithPublicKey encrypts data with a PEM public key and returns base64 encoded string func EncryptWithPublicKey(data string, pemBytes []byte) (string, error) { block, _ := pem.Decode(pemBytes) if block == nil { return "", errors.New("failed to parse PEM block containing the public key") } pub, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return "", err } pubKey, ok := pub.(*rsa.PublicKey) if !ok { return "", errors.New("not RSA public key") } ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, []byte(data)) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(ciphertext), nil }