Initial commit: Эфир мессенджер
This commit is contained in:
172
internal/crypto/aes.go
Normal file
172
internal/crypto/aes.go
Normal file
@@ -0,0 +1,172 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
type Encryptor struct {
|
||||
key []byte // 32 bytes for AES-256
|
||||
}
|
||||
|
||||
// NewEncryptor создает новый шифровальщик с заданным ключом
|
||||
// key должен быть 32 байта для AES-256
|
||||
func NewEncryptor(key []byte) (*Encryptor, error) {
|
||||
if len(key) != 32 {
|
||||
return nil, fmt.Errorf("encryption key must be 32 bytes, got %d", len(key))
|
||||
}
|
||||
|
||||
return &Encryptor{
|
||||
key: key,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Encrypt шифрует plaintext с использованием AES-GCM
|
||||
// Возвращает base64 encoded ciphertext с appended nonce
|
||||
func (e *Encryptor) Encrypt(plaintext []byte) (string, error) {
|
||||
if len(plaintext) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// Создаем блок AES
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create cipher: %w", err)
|
||||
}
|
||||
|
||||
// Создаем GCM режим
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create GCM: %w", err)
|
||||
}
|
||||
|
||||
// Генерируем случайный nonce
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", fmt.Errorf("failed to generate nonce: %w", err)
|
||||
}
|
||||
|
||||
// Шифруем: ciphertext = nonce + encrypted_data
|
||||
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
|
||||
|
||||
// Кодируем в base64 для хранения в БД
|
||||
encoded := base64.StdEncoding.EncodeToString(ciphertext)
|
||||
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
// Decrypt расшифровывает base64 encoded ciphertext
|
||||
// Ожидает формат: nonce + encrypted_data
|
||||
func (e *Encryptor) Decrypt(encodedCiphertext string) ([]byte, error) {
|
||||
if encodedCiphertext == "" {
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
// Декодируем из base64
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(encodedCiphertext)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode base64: %w", err)
|
||||
}
|
||||
|
||||
if len(ciphertext) == 0 {
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
// Создаем блок AES
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create cipher: %w", err)
|
||||
}
|
||||
|
||||
// Создаем GCM режим
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create GCM: %w", err)
|
||||
}
|
||||
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(ciphertext) < nonceSize {
|
||||
return nil, fmt.Errorf("ciphertext too short")
|
||||
}
|
||||
|
||||
// Извлекаем nonce и зашифрованные данные
|
||||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||
|
||||
// Расшифровываем
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decrypt: %w", err)
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
// EncryptString удобная обертка для шифрования строк
|
||||
func (e *Encryptor) EncryptString(plaintext string) (string, error) {
|
||||
return e.Encrypt([]byte(plaintext))
|
||||
}
|
||||
|
||||
// DecryptString удобная обертка для расшифровки в строку
|
||||
func (e *Encryptor) DecryptString(encodedCiphertext string) (string, error) {
|
||||
plaintext, err := e.Decrypt(encodedCiphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
// MustEncrypt паникует при ошибке шифрования (для инициализации)
|
||||
func (e *Encryptor) MustEncrypt(plaintext string) string {
|
||||
encrypted, err := e.EncryptString(plaintext)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("encryption failed: %v", err))
|
||||
}
|
||||
return encrypted
|
||||
}
|
||||
|
||||
// MustDecrypt паникует при ошибке расшифровки (для инициализации)
|
||||
func (e *Encryptor) MustDecrypt(encodedCiphertext string) string {
|
||||
decrypted, err := e.DecryptString(encodedCiphertext)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("decryption failed: %v", err))
|
||||
}
|
||||
return decrypted
|
||||
}
|
||||
|
||||
// GenerateRandomKey генерирует случайный 32-байтный ключ для AES-256
|
||||
func GenerateRandomKey() ([]byte, error) {
|
||||
key := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, key); err != nil {
|
||||
return nil, fmt.Errorf("failed to generate random key: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// GenerateRandomKeyString генерирует случайный ключ в виде hex строки
|
||||
func GenerateRandomKeyString() (string, error) {
|
||||
key, err := GenerateRandomKey()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// KeyFromString создает ключ из строки (ожидается 32 байта в base64 или plain)
|
||||
func KeyFromString(keyStr string) ([]byte, error) {
|
||||
// Пробуем декодировать как base64
|
||||
key, err := base64.StdEncoding.DecodeString(keyStr)
|
||||
if err == nil && len(key) == 32 {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// Если не base64, используем как есть (должно быть 32 байта)
|
||||
if len(keyStr) == 32 {
|
||||
return []byte(keyStr), nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid key length: expected 32 bytes, got %d", len(keyStr))
|
||||
}
|
||||
177
internal/crypto/aes_test.go
Normal file
177
internal/crypto/aes_test.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEncryptDecrypt(t *testing.T) {
|
||||
// Генерируем тестовый ключ
|
||||
key := make([]byte, 32)
|
||||
for i := range key {
|
||||
key[i] = byte(i)
|
||||
}
|
||||
|
||||
encryptor, err := NewEncryptor(key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create encryptor: %v", err)
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
plaintext string
|
||||
}{
|
||||
{"Empty string", ""},
|
||||
{"Simple text", "Hello, World!"},
|
||||
{"Russian text", "Привет, мир!"},
|
||||
{"Long text", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."},
|
||||
{"Special chars", "!@#$%^&*()_+-=[]{}|;:',.<>?/`~"},
|
||||
{"Emoji", "Hello 👋 World 🌍"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Шифруем
|
||||
encrypted, err := encryptor.EncryptString(tc.plaintext)
|
||||
if err != nil {
|
||||
t.Fatalf("Encryption failed: %v", err)
|
||||
}
|
||||
|
||||
// Проверяем, что зашифрованный текст не пустой (для непустого plaintext)
|
||||
if tc.plaintext != "" && encrypted == "" {
|
||||
t.Error("Encrypted text is empty for non-empty plaintext")
|
||||
}
|
||||
|
||||
// Расшифровываем
|
||||
decrypted, err := encryptor.DecryptString(encrypted)
|
||||
if err != nil {
|
||||
t.Fatalf("Decryption failed: %v", err)
|
||||
}
|
||||
|
||||
// Проверяем соответствие
|
||||
if decrypted != tc.plaintext {
|
||||
t.Errorf("Decrypted text doesn't match original.\nExpected: %s\nGot: %s", tc.plaintext, decrypted)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptDecryptBinary(t *testing.T) {
|
||||
key := make([]byte, 32)
|
||||
for i := range key {
|
||||
key[i] = byte(i)
|
||||
}
|
||||
|
||||
encryptor, err := NewEncryptor(key)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create encryptor: %v", err)
|
||||
}
|
||||
|
||||
// Тестируем бинарные данные
|
||||
binaryData := []byte{0x00, 0x01, 0x02, 0xFF, 0xFE, 0xFD}
|
||||
|
||||
encrypted, err := encryptor.Encrypt(binaryData)
|
||||
if err != nil {
|
||||
t.Fatalf("Encryption failed: %v", err)
|
||||
}
|
||||
|
||||
decrypted, err := encryptor.Decrypt(encrypted)
|
||||
if err != nil {
|
||||
t.Fatalf("Decryption failed: %v", err)
|
||||
}
|
||||
|
||||
if len(decrypted) != len(binaryData) {
|
||||
t.Errorf("Length mismatch: expected %d, got %d", len(binaryData), len(decrypted))
|
||||
}
|
||||
|
||||
for i := range binaryData {
|
||||
if decrypted[i] != binaryData[i] {
|
||||
t.Errorf("Byte mismatch at index %d: expected %d, got %d", i, binaryData[i], decrypted[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidKey(t *testing.T) {
|
||||
// Тестируем ключ неправильной длины
|
||||
invalidKey := make([]byte, 16)
|
||||
_, err := NewEncryptor(invalidKey)
|
||||
if err == nil {
|
||||
t.Error("Expected error for invalid key length, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecryptInvalidData(t *testing.T) {
|
||||
key := make([]byte, 32)
|
||||
encryptor, _ := NewEncryptor(key)
|
||||
|
||||
// Тестируем расшифровку некорректных данных
|
||||
invalidData := "not-a-valid-base64"
|
||||
_, err := encryptor.DecryptString(invalidData)
|
||||
if err == nil {
|
||||
t.Error("Expected error for invalid base64, got nil")
|
||||
}
|
||||
|
||||
// Тестируем расшифровку слишком коротких данных
|
||||
shortData := "aGVsbG8=" // "hello" в base64
|
||||
_, err = encryptor.DecryptString(shortData)
|
||||
if err == nil {
|
||||
t.Error("Expected error for too short ciphertext, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateRandomKey(t *testing.T) {
|
||||
key1, err := GenerateRandomKey()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
|
||||
if len(key1) != 32 {
|
||||
t.Errorf("Expected key length 32, got %d", len(key1))
|
||||
}
|
||||
|
||||
key2, err := GenerateRandomKey()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate second key: %v", err)
|
||||
}
|
||||
|
||||
// Проверяем, что ключи разные
|
||||
same := true
|
||||
for i := range key1 {
|
||||
if key1[i] != key2[i] {
|
||||
same = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if same {
|
||||
t.Error("Generated keys are identical")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkEncrypt(b *testing.B) {
|
||||
key := make([]byte, 32)
|
||||
encryptor, _ := NewEncryptor(key)
|
||||
plaintext := "This is a test message that will be encrypted repeatedly"
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, err := encryptor.EncryptString(plaintext)
|
||||
if err != nil {
|
||||
b.Fatalf("Encryption failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDecrypt(b *testing.B) {
|
||||
key := make([]byte, 32)
|
||||
encryptor, _ := NewEncryptor(key)
|
||||
plaintext := "This is a test message that will be encrypted repeatedly"
|
||||
encrypted, _ := encryptor.EncryptString(plaintext)
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, err := encryptor.DecryptString(encrypted)
|
||||
if err != nil {
|
||||
b.Fatalf("Decryption failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user