Files
purpleschool/go-demo-4/encrypter/encrypter.go
2025-03-19 23:37:15 +03:00

59 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package encrypter
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"os"
)
type Encrypter struct {
Key string
}
func NewEncrypter() *Encrypter {
key := os.Getenv("KEY")
if key == "" {
panic("Не передан параметр KEY в переменные окружения")
}
return &Encrypter{
Key: key,
}
}
func (enc *Encrypter) Encrypt(plainStr []byte) []byte {
block, err := aes.NewCipher([]byte(enc.Key))
if err != nil {
panic(err.Error())
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, aesGCM.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
panic(err.Error())
}
return aesGCM.Seal(nonce, nonce, plainStr, nil)
}
func (enc *Encrypter) Decrypt(encryptedStr []byte) []byte {
block, err := aes.NewCipher([]byte(enc.Key))
if err != nil {
panic(err.Error())
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := aesGCM.NonceSize()
nonce, cipherText := encryptedStr[:nonceSize], encryptedStr[nonceSize:]
plainText, err := aesGCM.Open(nil, nonce, cipherText, nil)
if err != nil {
panic(err.Error())
}
return plainText
}