common/utils/encrypted.go

58 lines
1.2 KiB
Go
Raw Normal View History

2024-03-22 12:06:18 +00:00
package utils
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}
}
2024-03-22 12:36:36 +00:00
func (e *Encrypt) EncryptStr(str string) ([]byte, error) {
2024-03-22 12:06:18 +00:00
block, _ := pem.Decode([]byte(e.pubKey))
if block == nil {
2024-03-22 12:36:36 +00:00
return nil, errors.New("failed to parse PEM block containing the public key")
2024-03-22 12:06:18 +00:00
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
2024-03-22 12:36:36 +00:00
return nil, err
2024-03-22 12:06:18 +00:00
}
rsaPubKey, ok := pub.(*rsa.PublicKey)
if !ok {
2024-03-22 12:36:36 +00:00
return nil, errors.New("failed to parse RSA public key")
2024-03-22 12:06:18 +00:00
}
shifr, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, []byte(str))
if err != nil {
2024-03-22 12:36:36 +00:00
return nil, err
2024-03-22 12:06:18 +00:00
}
2024-03-22 12:36:36 +00:00
return shifr, nil
2024-03-22 12:06:18 +00:00
}
2024-03-22 12:36:36 +00:00
func (e *Encrypt) DecryptStr(shifr []byte) (string, error) {
2024-03-22 12:06:18 +00:00
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
}
2024-03-22 12:36:36 +00:00
res, err := rsa.DecryptPKCS1v15(rand.Reader, priv, shifr)
2024-03-22 12:06:18 +00:00
if err != nil {
return "", err
}
return string(res), nil
}