add included
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"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(nil, pubKey, []byte(data))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
Reference in New Issue
Block a user