From 7536f12aa74f41e6f5f6b57e855402007b204fdf Mon Sep 17 00:00:00 2001 From: Archer Fox Date: Wed, 19 Mar 2025 23:37:15 +0300 Subject: [PATCH] Add encrypt and decrypt function --- .gitignore | 3 ++- go-demo-4/encrypter/encrypter.go | 43 ++++++++++++++++++++++++++++---- go-demo-4/main.go | 2 +- 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 7664412..bccaae3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ go-demo/app-1 go-demo-4/data.json -go-demo-4/.env +go-demo-4/.env* +go-demo-4/*.vault diff --git a/go-demo-4/encrypter/encrypter.go b/go-demo-4/encrypter/encrypter.go index d94eaff..bd38bbe 100644 --- a/go-demo-4/encrypter/encrypter.go +++ b/go-demo-4/encrypter/encrypter.go @@ -1,6 +1,12 @@ package encrypter -import "os" +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "io" + "os" +) type Encrypter struct { Key string @@ -16,10 +22,37 @@ func NewEncrypter() *Encrypter { } } -func (enc *Encrypter) Encrypt(plainStr string) string { - return "" +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 string) string { - return "" +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 } diff --git a/go-demo-4/main.go b/go-demo-4/main.go index 66f57dc..9f75f62 100644 --- a/go-demo-4/main.go +++ b/go-demo-4/main.go @@ -43,7 +43,7 @@ func main() { if err != nil { output.PrintError("Не удалось найти файл .env") } - vault := account.NewVault(files.NewJsonDb("data.json"), *encrypter.NewEncrypter()) + vault := account.NewVault(files.NewJsonDb("data.vault"), *encrypter.NewEncrypter()) counter := menuCounter() Menu: for {