Add encrypt and decrypt function

This commit is contained in:
Archer Fox
2025-03-19 23:37:15 +03:00
parent e7b8eb5601
commit 7536f12aa7
3 changed files with 41 additions and 7 deletions

3
.gitignore vendored
View File

@@ -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

View File

@@ -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
}

View File

@@ -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 {