common/encrypt/encrypted.go

54 lines
1.1 KiB
Go
Raw Normal View History

2024-11-20 14:15:01 +00:00
package encrypt
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
type Encrypt struct {
2024-11-26 12:11:30 +00:00
PubKey string `env:"ENCRYPT_PUBLIC_KEY"`
PrivKey string `env:"ENCRYPT_PRIVATE_KEY"`
2024-11-20 14:15:01 +00:00
}
func (e *Encrypt) EncryptStr(str string) ([]byte, error) {
2024-11-26 12:11:30 +00:00
block, _ := pem.Decode([]byte(e.PubKey))
2024-11-20 14:15:01 +00:00
if block == nil {
return nil, errors.New("failed to parse PEM block containing the public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
rsaPubKey, ok := pub.(*rsa.PublicKey)
if !ok {
return nil, errors.New("failed to parse RSA public key")
}
shifr, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, []byte(str))
if err != nil {
return nil, err
}
return shifr, nil
}
func (e *Encrypt) DecryptStr(shifr []byte) (string, error) {
2024-11-26 12:11:30 +00:00
block, _ := pem.Decode([]byte(e.PrivKey))
2024-11-20 14:15:01 +00:00
if block == nil {
return "", errors.New("failed to parse PEM block containing the private key")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
res, err := rsa.DecryptPKCS1v15(rand.Reader, priv, shifr)
if err != nil {
return "", err
}
return string(res), nil
}