dukcapil/internal/util/rsa_util.go
Aditya Siregar 2c43e758f5 fix rsa util
2026-05-07 09:48:37 +07:00

32 lines
791 B
Go

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
}