From 1695a0981562d8527e45103ae29851239db590ac Mon Sep 17 00:00:00 2001 From: Pasha Date: Wed, 20 Nov 2024 17:15:01 +0300 Subject: [PATCH] move package encrypt from quiz common --- encrypt/encrypted.go | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 encrypt/encrypted.go diff --git a/encrypt/encrypted.go b/encrypt/encrypted.go new file mode 100644 index 0000000..540c83a --- /dev/null +++ b/encrypt/encrypted.go @@ -0,0 +1,57 @@ +package encrypt + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +type Encrypt struct { + pubKey string + privKey string +} + +func NewEncrypt(pubKey, privKey string) *Encrypt { + return &Encrypt{pubKey: pubKey, privKey: privKey} +} + +func (e *Encrypt) EncryptStr(str string) ([]byte, error) { + block, _ := pem.Decode([]byte(e.pubKey)) + 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) { + block, _ := pem.Decode([]byte(e.privKey)) + 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 +}