💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add native crypto operations
Neeraj Gupta23a5914ea86f
diff --git a/server/pkg/utils/crypto/crypto.go b/server/pkg/utils/crypto/crypto.goindex 06913a7329..eb1b40e1f4 100644--- a/server/pkg/utils/crypto/crypto.go+++ b/server/pkg/utils/crypto/crypto.go@@ -12,17 +12,18 @@ import ("github.com/ente-io/museum/pkg/utils/auth")+// Exported constants matching libsodiumconst (- cryptoSecretBoxNonceBytes = 24 // Nonce size for secret box- // Generic hash (BLAKE2b) constants- cryptoGenericHashBytes = 32 // Default output size+ SecretBoxKeyBytes = 32 // crypto_secretbox_KEYBYTES in libsodium+ SecretBoxNonceBytes = 24 // crypto_secretbox_NONCEBYTES in libsodium+ GenericHashBytes = 32 // crypto_generichash_BYTES in libsodium (BLAKE2b-256))func Encrypt(data string, encryptionKey []byte) (ente.EncryptionResult, error) {- if cryptoSecretBoxNonceBytes != cryptosecretbox.CryptoSecretBoxNonceBytes() {- panic("cryptoSecretBoxNonceBytes constant does not match the actual nonce size")+ if SecretBoxNonceBytes != cryptosecretbox.CryptoSecretBoxNonceBytes() {+ panic("SecretBoxNonceBytes constant does not match the actual nonce size")}- nonce, err := auth.GenerateRandomBytes(cryptoSecretBoxNonceBytes)+ nonce, err := auth.GenerateRandomBytes(SecretBoxNonceBytes)if err != nil {return ente.EncryptionResult{}, stacktrace.Propagate(err, "")}@@ -46,11 +47,11 @@ func Decrypt(cipher []byte, key []byte, nonce []byte) (string, error) {}func GetHash(data string, hashKey []byte) (string, error) {- if cryptoGenericHashBytes != generichash.CryptoGenericHashBytes() {- panic(fmt.Sprintf("cryptoGenericHashBytes constant %d does not match the actual hash size %d",- cryptoGenericHashBytes, generichash.CryptoGenericHashBytes()))+ if GenericHashBytes != generichash.CryptoGenericHashBytes() {+ panic(fmt.Sprintf("GenericHashBytes constant %d does not match the actual hash size %d",+ GenericHashBytes, generichash.CryptoGenericHashBytes()))}- dataHashBytes, err := generichash.CryptoGenericHash(cryptoGenericHashBytes, []byte(data), hashKey)+ dataHashBytes, err := generichash.CryptoGenericHash(GenericHashBytes, []byte(data), hashKey)if err != 0 {return "", stacktrace.NewError("email hash failed")}diff --git a/server/pkg/utils/crypto/crypto_bench_test.go b/server/pkg/utils/crypto/crypto_bench_test.gonew file mode 100644index 0000000000..90fbacca05--- /dev/null+++ b/server/pkg/utils/crypto/crypto_bench_test.go@@ -0,0 +1,286 @@+package crypto++import (+ "encoding/base64"+ "testing"++ "github.com/ente-io/museum/ente"+)++func init() {+ // Initialize libsodium for benchmarks+ InitSodiumForTest()+}++// Benchmark encryption operations++func BenchmarkEncryptLibsodium(b *testing.B) {+ benchmarkEncrypt(b, Encrypt)+}++func BenchmarkEncryptNative(b *testing.B) {+ benchmarkEncrypt(b, EncryptNative)+}++func benchmarkEncrypt(b *testing.B, encryptFunc func(string, []byte) (ente.EncryptionResult, error)) {+ sizes := []struct {+ name string+ size int+ }{+ {"Small_32B", 32},+ {"Medium_1KB", 1024},+ {"Large_10KB", 10240},+ {"XLarge_100KB", 102400},+ {"Huge_1MB", 1048576},+ }++ for _, size := range sizes {+ b.Run(size.name, func(b *testing.B) {+ data := generateLargeText(size.size)+ key := generateTestKey()++ b.SetBytes(int64(size.size))+ b.ResetTimer()++ for i := 0; i < b.N; i++ {+ _, err := encryptFunc(data, key)+ if err != nil {+ b.Fatal(err)+ }+ }+ })+ }+}++// Benchmark decryption operations++func BenchmarkDecryptLibsodium(b *testing.B) {+ benchmarkDecrypt(b, Encrypt, Decrypt)+}++func BenchmarkDecryptNative(b *testing.B) {+ benchmarkDecrypt(b, EncryptNative, DecryptNative)+}++func benchmarkDecrypt(b *testing.B,+ encryptFunc func(string, []byte) (ente.EncryptionResult, error),+ decryptFunc func([]byte, []byte, []byte) (string, error)) {++ sizes := []struct {+ name string+ size int+ }{+ {"Small_32B", 32},+ {"Medium_1KB", 1024},+ {"Large_10KB", 10240},+ {"XLarge_100KB", 102400},+ {"Huge_1MB", 1048576},+ }++ for _, size := range sizes {+ b.Run(size.name, func(b *testing.B) {+ data := generateLargeText(size.size)+ key := generateTestKey()++ // Encrypt once for benchmark+ encResult, err := encryptFunc(data, key)+ if err != nil {+ b.Fatal(err)+ }++ cipher := encResult.Cipher+ nonce := encResult.Nonce++ b.SetBytes(int64(size.size))+ b.ResetTimer()++ for i := 0; i < b.N; i++ {+ _, err := decryptFunc(cipher, key, nonce)+ if err != nil {+ b.Fatal(err)+ }+ }+ })+ }+}++// Benchmark hash operations++func BenchmarkHashLibsodium(b *testing.B) {+ benchmarkHash(b, GetHash)+}++func BenchmarkHashNative(b *testing.B) {+ benchmarkHash(b, GetHashNative)+}++func benchmarkHash(b *testing.B, hashFunc func(string, []byte) (string, error)) {+ sizes := []struct {+ name string+ size int+ }{+ {"Small_32B", 32},+ {"Medium_1KB", 1024},+ {"Large_10KB", 10240},+ {"XLarge_100KB", 102400},+ {"Huge_1MB", 1048576},+ }++ for _, size := range sizes {+ b.Run(size.name, func(b *testing.B) {+ data := generateLargeText(size.size)++ b.SetBytes(int64(size.size))+ b.ResetTimer()++ for i := 0; i < b.N; i++ {+ _, err := hashFunc(data, nil)+ if err != nil {+ b.Fatal(err)+ }+ }+ })+ }+}++// Benchmark token encryption (sealed box)++func BenchmarkGetEncryptedTokenLibsodium(b *testing.B) {+ benchmarkGetEncryptedToken(b, GetEncryptedToken)+}++func BenchmarkGetEncryptedTokenNative(b *testing.B) {+ benchmarkGetEncryptedToken(b, GetEncryptedTokenNative)+}++func benchmarkGetEncryptedToken(b *testing.B, tokenFunc func(string, string) (string, error)) {+ // Generate test public key+ publicKey := make([]byte, 32)+ for i := range publicKey {+ publicKey[i] = byte(i * 3)+ }+ publicKeyB64 := base64.StdEncoding.EncodeToString(publicKey)++ sizes := []struct {+ name string+ size int+ }{+ {"Small_32B", 32},+ {"Medium_256B", 256},+ {"Large_1KB", 1024},+ }++ for _, size := range sizes {+ b.Run(size.name, func(b *testing.B) {+ tokenData := generateLargeText(size.size)+ token := base64.URLEncoding.EncodeToString([]byte(tokenData))++ b.SetBytes(int64(size.size))+ b.ResetTimer()++ for i := 0; i < b.N; i++ {+ _, err := tokenFunc(token, publicKeyB64)+ if err != nil {+ b.Fatal(err)+ }+ }+ })+ }+}++// Combined encryption/decryption cycle benchmark++func BenchmarkFullCycleLibsodium(b *testing.B) {+ benchmarkFullCycle(b, Encrypt, Decrypt)+}++func BenchmarkFullCycleNative(b *testing.B) {+ benchmarkFullCycle(b, EncryptNative, DecryptNative)+}++func benchmarkFullCycle(b *testing.B,+ encryptFunc func(string, []byte) (ente.EncryptionResult, error),+ decryptFunc func([]byte, []byte, []byte) (string, error)) {++ sizes := []struct {+ name string+ size int+ }{+ {"Small_32B", 32},+ {"Medium_1KB", 1024},+ {"Large_10KB", 10240},+ {"XLarge_100KB", 102400},+ }++ for _, size := range sizes {+ b.Run(size.name, func(b *testing.B) {+ data := generateLargeText(size.size)+ key := generateTestKey()++ b.SetBytes(int64(size.size * 2)) // Count both encrypt and decrypt+ b.ResetTimer()++ for i := 0; i < b.N; i++ {+ encResult, err := encryptFunc(data, key)+ if err != nil {+ b.Fatal(err)+ }++ cipher := encResult.Cipher+ nonce := encResult.Nonce++ _, err = decryptFunc(cipher, key, nonce)+ if err != nil {+ b.Fatal(err)+ }+ }+ })+ }+}++// Memory allocation benchmarks++func BenchmarkMemoryAllocLibsodium(b *testing.B) {+ b.ReportAllocs()+ data := generateLargeText(1024)+ key := generateTestKey()++ for i := 0; i < b.N; i++ {+ _, _ = Encrypt(data, key)+ }+}++func BenchmarkMemoryAllocNative(b *testing.B) {+ b.ReportAllocs()+ data := generateLargeText(1024)+ key := generateTestKey()++ for i := 0; i < b.N; i++ {+ _, _ = EncryptNative(data, key)+ }+}++// Parallel benchmarks to test concurrent performance++func BenchmarkParallelEncryptLibsodium(b *testing.B) {+ data := generateLargeText(1024)+ key := generateTestKey()++ b.RunParallel(func(pb *testing.PB) {+ for pb.Next() {+ _, _ = Encrypt(data, key)+ }+ })+}++func BenchmarkParallelEncryptNative(b *testing.B) {+ data := generateLargeText(1024)+ key := generateTestKey()++ b.RunParallel(func(pb *testing.PB) {+ for pb.Next() {+ _, _ = EncryptNative(data, key)+ }+ })+}+diff --git a/server/pkg/utils/crypto/crypto_enhanced_test.go b/server/pkg/utils/crypto/crypto_enhanced_test.gonew file mode 100644index 0000000000..86ad3e3639--- /dev/null+++ b/server/pkg/utils/crypto/crypto_enhanced_test.go@@ -0,0 +1,426 @@+package crypto++import (+ "encoding/base64"+ "fmt"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// Test real-world scenarios based on codebase usage++func TestRealWorldEmailEncryption(t *testing.T) {+ // Simulating email encryption as used in user controller+ secretEncryptionKey := generateTestKey()++ emails := []string{+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ // Edge cases found in production+ "[email protected]",+ "[email protected]",+ "user@例え.jp", // IDN domain+ "very.long.email.address.with.many.dots@subdomain.of.a.domain.example.com",+ }++ for _, email := range emails {+ t.Run(fmt.Sprintf("email_%s", strings.ReplaceAll(email, "@", "_at_")), func(t *testing.T) {+ // Test with libsodium+ encryptedLib, err := Encrypt(email, secretEncryptionKey)+ require.NoError(t, err)++ // Test with native+ encryptedNative, err := EncryptNative(email, secretEncryptionKey)+ require.NoError(t, err)++ // Cross-decrypt+ decryptedFromLib, err := DecryptNative(encryptedLib.Cipher, secretEncryptionKey, encryptedLib.Nonce)+ require.NoError(t, err)+ assert.Equal(t, email, decryptedFromLib)++ decryptedFromNative, err := Decrypt(encryptedNative.Cipher, secretEncryptionKey, encryptedNative.Nonce)+ require.NoError(t, err)+ assert.Equal(t, email, decryptedFromNative)+ })+ }+}++func TestRealWorldSecretEncryption(t *testing.T) {+ // Simulating 2FA secret encryption as used in twofactor controller+ secretEncryptionKey := generateTestKey()++ secrets := []string{+ "JBSWY3DPEHPK3PXP", // Standard TOTP secret+ "MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPF4GIZLDOQWXI", // Longer secret+ "abcdefghijklmnopqrstuvwxyz234567", // Base32 alphabet+ "ABCDEFGHIJKLMNOP", // Short secret+ strings.Repeat("A", 256), // Large secret+ }++ for _, secret := range secrets {+ t.Run(fmt.Sprintf("secret_len_%d", len(secret)), func(t *testing.T) {+ // Encrypt with both implementations+ encryptedLib, err := Encrypt(secret, secretEncryptionKey)+ require.NoError(t, err)++ encryptedNative, err := EncryptNative(secret, secretEncryptionKey)+ require.NoError(t, err)++ // Verify both can decrypt each other+ decryptedLib, err := Decrypt(encryptedNative.Cipher, secretEncryptionKey, encryptedNative.Nonce)+ require.NoError(t, err)+ assert.Equal(t, secret, decryptedLib)++ decryptedNative, err := DecryptNative(encryptedLib.Cipher, secretEncryptionKey, encryptedLib.Nonce)+ require.NoError(t, err)+ assert.Equal(t, secret, decryptedNative)+ })+ }+}++func TestRealWorldHashingWithKey(t *testing.T) {+ // Simulating email and secret hashing as used in the codebase+ hashingKeys := [][]byte{+ nil, // Some hashes use nil key+ generateTestKey(), // 32-byte key+ []byte("sixteen-byte-key"), // 16-byte key (minimum for libsodium)+ []byte(strings.Repeat("x", 64)), // 64-byte key (maximum for libsodium)+ }++ inputs := []string{+ "[email protected]",+ "[email protected]",+ strings.ToLower("[email protected]"), // Email normalization+ "JBSWY3DPEHPK3PXP", // TOTP secret+ "", // Edge case - empty string (skip for libsodium due to bug)+ strings.Repeat("a", 10000), // Large input+ }++ for _, key := range hashingKeys {+ keyName := "nil"+ if key != nil {+ keyName = fmt.Sprintf("key_len_%d", len(key))+ }++ for _, input := range inputs {+ if input == "" {+ continue // Skip empty string due to libsodium-go bug+ }++ t.Run(fmt.Sprintf("%s_input_%d_chars", keyName, len(input)), func(t *testing.T) {+ hashLib, err := GetHash(input, key)+ require.NoError(t, err)++ hashNative, err := GetHashNative(input, key)+ require.NoError(t, err)++ assert.Equal(t, hashLib, hashNative, "Hashes should match")++ // Verify hash is deterministic+ hashLib2, err := GetHash(input, key)+ require.NoError(t, err)+ assert.Equal(t, hashLib, hashLib2, "Hash should be deterministic")++ hashNative2, err := GetHashNative(input, key)+ require.NoError(t, err)+ assert.Equal(t, hashNative, hashNative2, "Native hash should be deterministic")+ })+ }+ }+}++func TestRealWorldTokenEncryption(t *testing.T) {+ // Simulating token encryption with public keys as used in auth++ // Generate test public keys+ publicKey1 := make([]byte, 32)+ for i := range publicKey1 {+ publicKey1[i] = byte(i + 1)+ }++ publicKey2 := make([]byte, 32)+ for i := range publicKey2 {+ publicKey2[i] = byte(i * 2)+ }++ publicKeys := []string{+ base64.StdEncoding.EncodeToString(publicKey1),+ base64.StdEncoding.EncodeToString(publicKey2),+ }++ tokens := []string{+ // JWT-like tokens+ base64.URLEncoding.EncodeToString([]byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")),+ // Session tokens+ base64.URLEncoding.EncodeToString([]byte("session_1234567890")),+ // Random tokens+ base64.URLEncoding.EncodeToString([]byte(strings.Repeat("x", 64))),+ }++ for _, publicKey := range publicKeys {+ for i, token := range tokens {+ t.Run(fmt.Sprintf("token_%d", i), func(t *testing.T) {+ // Both implementations should produce valid sealed boxes+ encryptedLib, err := GetEncryptedToken(token, publicKey)+ require.NoError(t, err)++ encryptedNative, err := GetEncryptedTokenNative(token, publicKey)+ require.NoError(t, err)++ // Verify format (ephemeral public key + ciphertext)+ encryptedLibBytes, err := base64.StdEncoding.DecodeString(encryptedLib)+ require.NoError(t, err)+ assert.GreaterOrEqual(t, len(encryptedLibBytes), 48, "Should have ephemeral key (32) + MAC (16)")++ encryptedNativeBytes, err := base64.StdEncoding.DecodeString(encryptedNative)+ require.NoError(t, err)+ assert.GreaterOrEqual(t, len(encryptedNativeBytes), 48, "Should have ephemeral key (32) + MAC (16)")+ })+ }+ }+}++func TestMigrationScenarios(t *testing.T) {+ // Test scenarios for migrating from libsodium to native++ t.Run("existing_encrypted_data_compatibility", func(t *testing.T) {+ // Simulate existing data encrypted with libsodium+ data := "[email protected]"+ key := generateTestKey()++ // Encrypt with libsodium (simulating existing data)+ existingEncrypted, err := Encrypt(data, key)+ require.NoError(t, err)++ // Ensure native can decrypt existing data+ decrypted, err := DecryptNative(existingEncrypted.Cipher, key, existingEncrypted.Nonce)+ require.NoError(t, err)+ assert.Equal(t, data, decrypted, "Native should decrypt existing libsodium data")+ })++ t.Run("new_data_backward_compatibility", func(t *testing.T) {+ // Simulate new data encrypted with native+ data := "[email protected]"+ key := generateTestKey()++ // Encrypt with native (new implementation)+ newEncrypted, err := EncryptNative(data, key)+ require.NoError(t, err)++ // Ensure libsodium can still decrypt if needed+ decrypted, err := Decrypt(newEncrypted.Cipher, key, newEncrypted.Nonce)+ require.NoError(t, err)+ assert.Equal(t, data, decrypted, "Libsodium should decrypt native encrypted data")+ })++ t.Run("hash_consistency_across_migration", func(t *testing.T) {+ // Critical for email lookups and authentication+ email := "[email protected]"+ hashingKey := []byte("production-hashing-key-32-bytes!")++ // Hash with both implementations+ hashLib, err := GetHash(email, hashingKey)+ require.NoError(t, err)++ hashNative, err := GetHashNative(email, hashingKey)+ require.NoError(t, err)++ // MUST be identical for database lookups to work+ assert.Equal(t, hashLib, hashNative, "Hashes must be identical for migration")+ })+}++func TestProductionEdgeCases(t *testing.T) {+ key := generateTestKey()++ t.Run("unicode_data", func(t *testing.T) {+ // Test with various unicode strings+ unicodeStrings := []string{+ "Hello 世界 🌍",+ "Здравствуй мир",+ "مرحبا بالعالم",+ "🔐🔑🗝️",+ "user@日本.jp",+ }++ for _, s := range unicodeStrings {+ encLib, err := Encrypt(s, key)+ require.NoError(t, err)++ encNative, err := EncryptNative(s, key)+ require.NoError(t, err)++ // Cross-decrypt+ decLib, err := DecryptNative(encLib.Cipher, key, encLib.Nonce)+ require.NoError(t, err)+ assert.Equal(t, s, decLib)++ decNative, err := Decrypt(encNative.Cipher, key, encNative.Nonce)+ require.NoError(t, err)+ assert.Equal(t, s, decNative)+ }+ })++ t.Run("binary_data", func(t *testing.T) {+ // Test with binary data (non-UTF8)+ binaryData := []string{+ string([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}),+ string([]byte{255, 254, 253, 252, 251}),+ "\x00\x01\x02\x03",+ }++ for _, data := range binaryData {+ encLib, err := Encrypt(data, key)+ require.NoError(t, err)++ encNative, err := EncryptNative(data, key)+ require.NoError(t, err)++ // Both should handle binary data correctly+ decLib, err := DecryptNative(encLib.Cipher, key, encLib.Nonce)+ require.NoError(t, err)+ assert.Equal(t, data, decLib)++ decNative, err := Decrypt(encNative.Cipher, key, encNative.Nonce)+ require.NoError(t, err)+ assert.Equal(t, data, decNative)+ }+ })++ t.Run("very_large_data", func(t *testing.T) {+ // Test with large data (e.g., large JSON payloads)+ sizes := []int{+ 10 * 1024, // 10KB+ 100 * 1024, // 100KB+ 1024 * 1024, // 1MB+ }++ for _, size := range sizes {+ t.Run(fmt.Sprintf("size_%d", size), func(t *testing.T) {+ largeData := strings.Repeat("a", size)++ // Encrypt with native (faster based on benchmarks)+ encNative, err := EncryptNative(largeData, key)+ require.NoError(t, err)++ // Decrypt with libsodium to verify compatibility+ decLib, err := Decrypt(encNative.Cipher, key, encNative.Nonce)+ require.NoError(t, err)+ assert.Equal(t, largeData, decLib)+ })+ }+ })+}++func TestConcurrentOperations(t *testing.T) {+ // Test thread-safety of both implementations+ key := generateTestKey()+ hashKey := []byte("concurrent-hash-key-test-32byte!")++ t.Run("concurrent_encryption", func(t *testing.T) {+ data := []string{+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ }++ // Run concurrent encryptions+ results := make(chan bool, len(data)*2)++ for _, d := range data {+ go func(text string) {+ enc, err := EncryptNative(text, key)+ assert.NoError(t, err)+ dec, err := DecryptNative(enc.Cipher, key, enc.Nonce)+ assert.NoError(t, err)+ results <- (dec == text)+ }(d)++ go func(text string) {+ enc, err := Encrypt(text, key)+ assert.NoError(t, err)+ dec, err := Decrypt(enc.Cipher, key, enc.Nonce)+ assert.NoError(t, err)+ results <- (dec == text)+ }(d)+ }++ // Verify all succeeded+ for i := 0; i < len(data)*2; i++ {+ assert.True(t, <-results)+ }+ })++ t.Run("concurrent_hashing", func(t *testing.T) {+ inputs := []string{+ "[email protected]",+ "[email protected]",+ "[email protected]",+ }++ results := make(chan string, len(inputs)*2)++ for _, input := range inputs {+ go func(text string) {+ hash, err := GetHashNative(text, hashKey)+ assert.NoError(t, err)+ results <- hash+ }(input)++ go func(text string) {+ hash, err := GetHash(text, hashKey)+ assert.NoError(t, err)+ results <- hash+ }(input)+ }++ // Collect and verify consistency+ hashes := make(map[string]int)+ for i := 0; i < len(inputs)*2; i++ {+ h := <-results+ hashes[h]+++ }++ // Each input should produce the same hash twice (once from each impl)+ for _, count := range hashes {+ assert.Equal(t, 2, count, "Each hash should appear exactly twice")+ }+ })+}++func TestDeterministicBehavior(t *testing.T) {+ // Critical test: Ensure deterministic behavior with same nonce+ key := generateTestKey()+ data := "[email protected]"++ // Use a fixed nonce for testing+ fixedNonce := make([]byte, SecretBoxNonceBytes)+ for i := range fixedNonce {+ fixedNonce[i] = byte(i * 3)+ }++ // Encrypt multiple times with same nonce+ enc1, err := encryptWithNonce(data, key, fixedNonce)+ require.NoError(t, err)++ enc2, err := encryptWithNonce(data, key, fixedNonce)+ require.NoError(t, err)++ encNative1, err := encryptWithNonceNative(data, key, fixedNonce)+ require.NoError(t, err)++ encNative2, err := encryptWithNonceNative(data, key, fixedNonce)+ require.NoError(t, err)++ // All should be identical+ assert.Equal(t, enc1.Cipher, enc2.Cipher, "Libsodium should be deterministic with same nonce")+ assert.Equal(t, encNative1.Cipher, encNative2.Cipher, "Native should be deterministic with same nonce")+ assert.Equal(t, enc1.Cipher, encNative1.Cipher, "Both implementations should produce same output with same nonce")+}diff --git a/server/pkg/utils/crypto/crypto_native.go b/server/pkg/utils/crypto/crypto_native.gonew file mode 100644index 0000000000..085fbec06c--- /dev/null+++ b/server/pkg/utils/crypto/crypto_native.go@@ -0,0 +1,134 @@+package crypto++import (+ "crypto/rand"+ "encoding/base64"+ "github.com/ente-io/museum/pkg/utils/auth"++ "github.com/ente-io/museum/ente"+ "github.com/ente-io/stacktrace"+ "golang.org/x/crypto/blake2b"+ "golang.org/x/crypto/nacl/box"+ "golang.org/x/crypto/nacl/secretbox"+)++func EncryptNative(data string, encryptionKey []byte) (ente.EncryptionResult, error) {+ // Generate nonce+ nonce, err := auth.GenerateRandomBytes(SecretBoxNonceBytes)+ if err != nil {+ return ente.EncryptionResult{}, stacktrace.Propagate(err, "")+ }+ return encryptWithNonceNative(data, encryptionKey, nonce)+}++func encryptWithNonceNative(data string, encryptionKey []byte, nonce []byte) (ente.EncryptionResult, error) {+ // Convert key to array+ if len(encryptionKey) != SecretBoxKeyBytes {+ return ente.EncryptionResult{}, stacktrace.NewError("invalid key length")+ }+ var key [32]byte+ copy(key[:], encryptionKey)++ // Convert nonce to array+ if len(nonce) != SecretBoxNonceBytes {+ return ente.EncryptionResult{}, stacktrace.NewError("invalid nonce length")+ }+ var nonceArray [SecretBoxNonceBytes]byte+ copy(nonceArray[:], nonce)++ // Encrypt using secretbox (XSalsa20-Poly1305)+ encrypted := secretbox.Seal(nil, []byte(data), &nonceArray, &key)++ return ente.EncryptionResult{+ Cipher: encrypted,+ Nonce: nonce,+ }, nil+}++func DecryptNative(cipher []byte, encryptionKey []byte, nonce []byte) (string, error) {+ cipherBytes := cipher+ nonceBytes := nonce++ // Convert key to array+ if len(encryptionKey) != SecretBoxKeyBytes {+ return "", stacktrace.NewError("invalid key length")+ }+ var key [32]byte+ copy(key[:], encryptionKey)++ // Convert nonce to array+ if len(nonceBytes) != SecretBoxNonceBytes {+ return "", stacktrace.NewError("invalid nonce length")+ }+ var nonceArray [SecretBoxNonceBytes]byte+ copy(nonceArray[:], nonceBytes)++ // Decrypt using secretbox+ decrypted, ok := secretbox.Open(nil, cipherBytes, &nonceArray, &key)+ if !ok {+ return "", stacktrace.NewError("decryption failed")+ }++ return string(decrypted), nil+}++func GetHashNative(data string, hashKey []byte) (string, error) {+ // BLAKE2b-256 hash with optional key+ hash, err := blake2b.New256(hashKey)+ if err != nil {+ return "", stacktrace.Propagate(err, "failed to create blake2b hasher")+ }++ hash.Write([]byte(data))+ hashBytes := hash.Sum(nil)++ return base64.StdEncoding.EncodeToString(hashBytes), nil+}++func GetEncryptedTokenNative(token string, publicKey string) (string, error) {+ publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKey)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if len(publicKeyBytes) != 32 {+ return "", stacktrace.NewError("invalid public key length")+ }++ tokenBytes, err := base64.URLEncoding.DecodeString(token)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }++ // Convert slice to array for nacl/box+ var recipientPublicKey [32]byte+ copy(recipientPublicKey[:], publicKeyBytes)++ // Generate ephemeral keypair+ ephemeralPublicKey, ephemeralPrivateKey, err := box.GenerateKey(rand.Reader)+ if err != nil {+ return "", stacktrace.Propagate(err, "failed to generate ephemeral keypair")+ }++ // Derive nonce deterministically like libsodium's crypto_box_seal+ // nonce = BLAKE2b-192(ephemeral_pk || recipient_pk)+ nonceInput := make([]byte, 64)+ copy(nonceInput[:32], ephemeralPublicKey[:])+ copy(nonceInput[32:], recipientPublicKey[:])++ hash, err := blake2b.New(24, nil) // 24 bytes = 192 bits for nonce+ if err != nil {+ return "", stacktrace.Propagate(err, "failed to create blake2b hasher")+ }+ hash.Write(nonceInput)+ var nonce [24]byte+ copy(nonce[:], hash.Sum(nil))++ // Encrypt the message (ephemeral public key + ciphertext)+ // Format matches libsodium: ephemeral_pk || box(m, nonce, recipient_pk, ephemeral_sk)+ out := make([]byte, 32) // just ephemeral public key+ copy(out, ephemeralPublicKey[:])++ encrypted := box.Seal(out, tokenBytes, &nonce, &recipientPublicKey, ephemeralPrivateKey)++ return base64.StdEncoding.EncodeToString(encrypted), nil+}diff --git a/server/pkg/utils/crypto/crypto_test.go b/server/pkg/utils/crypto/crypto_test.gonew file mode 100644index 0000000000..870025a238--- /dev/null+++ b/server/pkg/utils/crypto/crypto_test.go@@ -0,0 +1,305 @@+package crypto++import (+ "encoding/base64"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func init() {+ // Initialize libsodium+ InitSodiumForTest()+}++func TestEncryptWithSameNonce(t *testing.T) {+ // Test that both implementations produce identical output with the same nonce+ data := "Hello, World!"+ key := generateTestKey()++ // Generate a fixed nonce+ nonce := make([]byte, SecretBoxNonceBytes)+ for i := range nonce {+ nonce[i] = byte(i * 7)+ }++ // Encrypt with libsodium+ encryptedLibsodium, err := encryptWithNonce(data, key, nonce)+ require.NoError(t, err, "libsodium encryption should succeed")++ // Encrypt with native+ encryptedNative, err := encryptWithNonceNative(data, key, nonce)+ require.NoError(t, err, "native encryption should succeed")++ // Check that ciphertext is identical+ assert.Equal(t, encryptedLibsodium.Cipher, encryptedNative.Cipher, "ciphertext should be identical")+ assert.Equal(t, encryptedLibsodium.Nonce, encryptedNative.Nonce, "nonce should be identical")++ // Verify both can decrypt each other's output+ decryptedFromLibsodium, err := DecryptNative(encryptedLibsodium.Cipher, key, encryptedLibsodium.Nonce)+ require.NoError(t, err, "native should decrypt libsodium ciphertext")+ assert.Equal(t, data, decryptedFromLibsodium)++ decryptedFromNative, err := Decrypt(encryptedNative.Cipher, key, encryptedNative.Nonce)+ require.NoError(t, err, "libsodium should decrypt native ciphertext")+ assert.Equal(t, data, decryptedFromNative)+}++func TestEncryptDecryptCompatibility(t *testing.T) {+ tests := []struct {+ name string+ data string+ key []byte+ }{+ {+ name: "simple text",+ data: "Hello, World!",+ key: generateTestKey(),+ },+ // Skip empty string test - libsodium-go wrapper has a bug with empty strings+ // {+ // name: "empty string",+ // data: "",+ // key: generateTestKey(),+ // },+ {+ name: "special characters",+ data: "!@#$%^&*()_+-=[]{}|;':\",./<>?",+ key: generateTestKey(),+ },+ {+ name: "unicode characters",+ data: "你好世界 🌍 مرحبا بالعالم",+ key: generateTestKey(),+ },+ {+ name: "large text",+ data: generateLargeText(10000),+ key: generateTestKey(),+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ // Test libsodium encryption -> native decryption+ t.Run("libsodium_encrypt_native_decrypt", func(t *testing.T) {+ encrypted, err := Encrypt(tt.data, tt.key)+ require.NoError(t, err, "libsodium encryption should succeed")++ decrypted, err := DecryptNative(encrypted.Cipher, tt.key, encrypted.Nonce)+ require.NoError(t, err, "native decryption should succeed")+ assert.Equal(t, tt.data, decrypted, "decrypted data should match original")+ })++ // Test native encryption -> libsodium decryption+ t.Run("native_encrypt_libsodium_decrypt", func(t *testing.T) {+ encrypted, err := EncryptNative(tt.data, tt.key)+ require.NoError(t, err, "native encryption should succeed")++ decrypted, err := Decrypt(encrypted.Cipher, tt.key, encrypted.Nonce)+ require.NoError(t, err, "libsodium decryption should succeed")+ assert.Equal(t, tt.data, decrypted, "decrypted data should match original")+ })++ // Test self-consistency of native implementation+ t.Run("native_self_consistency", func(t *testing.T) {+ encrypted, err := EncryptNative(tt.data, tt.key)+ require.NoError(t, err, "native encryption should succeed")++ decrypted, err := DecryptNative(encrypted.Cipher, tt.key, encrypted.Nonce)+ require.NoError(t, err, "native decryption should succeed")+ assert.Equal(t, tt.data, decrypted, "decrypted data should match original")+ })++ // Test self-consistency of libsodium implementation+ t.Run("libsodium_self_consistency", func(t *testing.T) {+ encrypted, err := Encrypt(tt.data, tt.key)+ require.NoError(t, err, "libsodium encryption should succeed")++ decrypted, err := Decrypt(encrypted.Cipher, tt.key, encrypted.Nonce)+ require.NoError(t, err, "libsodium decryption should succeed")+ assert.Equal(t, tt.data, decrypted, "decrypted data should match original")+ })+ })+ }+}++func TestHashCompatibility(t *testing.T) {+ tests := []struct {+ name string+ data string+ }{+ {+ name: "simple text",+ data: "Hello, World!",+ },+ {+ name: "empty string",+ data: "",+ },+ {+ name: "special characters",+ data: "!@#$%^&*()_+-=[]{}|;':\",./<>?",+ },+ {+ name: "unicode characters",+ data: "你好世界 🌍 مرحبا بالعالم",+ },+ {+ name: "large text",+ data: generateLargeText(10000),+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ hashLibsodium, err := GetHash(tt.data, nil)+ require.NoError(t, err, "libsodium hash should succeed")++ hashNative, err := GetHashNative(tt.data, nil)+ require.NoError(t, err, "native hash should succeed")++ assert.Equal(t, hashLibsodium, hashNative, "hashes should match")+ })+ }+}++func TestGetEncryptedTokenCompatibility(t *testing.T) {+ // Generate test keypair for recipient+ recipientPublicKey, _ := generateTestKeyPair()+ recipientPublicKeyB64 := base64.StdEncoding.EncodeToString(recipientPublicKey[:])++ tests := []struct {+ name string+ token string+ }{+ {+ name: "simple token",+ token: base64.URLEncoding.EncodeToString([]byte("test-token-123")),+ },+ {+ name: "complex token",+ token: base64.URLEncoding.EncodeToString([]byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0")),+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ // Test that both implementations produce valid sealed boxes+ // We can't compare the encrypted values directly because they use random ephemeral keys++ // Test libsodium implementation produces valid output+ t.Run("libsodium_valid_output", func(t *testing.T) {+ encrypted, err := GetEncryptedToken(tt.token, recipientPublicKeyB64)+ require.NoError(t, err, "libsodium encryption should succeed")++ // Verify output format+ encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)+ require.NoError(t, err, "should decode encrypted token")+ // Sealed box format: ephemeral_pk (32 bytes) + ciphertext+ assert.GreaterOrEqual(t, len(encryptedBytes), 32+16, "should have ephemeral key and ciphertext")+ })++ // Test native implementation produces valid output+ t.Run("native_valid_output", func(t *testing.T) {+ encrypted, err := GetEncryptedTokenNative(tt.token, recipientPublicKeyB64)+ require.NoError(t, err, "native encryption should succeed")++ // Verify output format+ encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)+ require.NoError(t, err, "should decode encrypted token")+ // Sealed box format: ephemeral_pk (32 bytes) + ciphertext+ assert.GreaterOrEqual(t, len(encryptedBytes), 32+16, "should have ephemeral key and ciphertext")+ })++ // Test that both can decrypt each other's output+ // Note: We would need the decrypt sealed box function to fully test compatibility+ // For now we just verify the format is correct+ })+ }+}++func TestErrorCases(t *testing.T) {+ validKey := generateTestKey()++ t.Run("invalid_key_length", func(t *testing.T) {+ // Test with wrong key length+ shortKey := []byte("too-short")++ _, err := EncryptNative("test", shortKey)+ assert.Error(t, err, "should error with short key")++ _, err = DecryptNative([]byte("test"), shortKey, []byte("nonce"))+ assert.Error(t, err, "should error with short key")+ })++ t.Run("invalid_nonce_length", func(t *testing.T) {+ // Test decrypt with wrong nonce length+ encrypted, err := EncryptNative("test", validKey)+ require.NoError(t, err)++ _, err = DecryptNative(encrypted.Cipher, validKey, []byte("short"))+ assert.Error(t, err, "should error with short nonce")+ })++ t.Run("tampered_ciphertext", func(t *testing.T) {+ encrypted, err := EncryptNative("test", validKey)+ require.NoError(t, err)++ // Tamper with ciphertext+ cipherBytes := make([]byte, len(encrypted.Cipher))+ copy(cipherBytes, encrypted.Cipher)+ if len(cipherBytes) > 0 {+ cipherBytes[0] ^= 0xFF // Flip bits+ }++ _, err = DecryptNative(cipherBytes, validKey, encrypted.Nonce)+ assert.Error(t, err, "should error with tampered ciphertext")+ })++ t.Run("wrong_key_decrypt", func(t *testing.T) {+ wrongKey := make([]byte, 32)+ for i := range wrongKey {+ wrongKey[i] = byte(i + 100) // Different pattern from validKey+ }++ encrypted, err := EncryptNative("test", validKey)+ require.NoError(t, err)++ _, err = DecryptNative(encrypted.Cipher, wrongKey, encrypted.Nonce)+ assert.Error(t, err, "should error with wrong key")+ })+}++// Helper functions++func generateTestKey() []byte {+ key := make([]byte, SecretBoxKeyBytes)+ for i := range key {+ key[i] = byte(i)+ }+ return key+}++func generateTestKeyPair() ([32]byte, [32]byte) {+ // Generate a deterministic test keypair for testing+ var publicKey, privateKey [32]byte+ // Use a fixed seed for deterministic testing+ seed := make([]byte, 32)+ for i := range seed {+ seed[i] = byte(i * 2)+ }+ copy(privateKey[:], seed)+ // This is a simplified test keypair - in real usage use box.GenerateKey+ copy(publicKey[:], append([]byte("public"), seed[:26]...))+ return publicKey, privateKey+}++func generateLargeText(size int) string {+ text := make([]byte, size)+ for i := range text {+ text[i] = byte('a' + (i % 26))+ }+ return string(text)+}diff --git a/server/pkg/utils/crypto/test_init.go b/server/pkg/utils/crypto/test_init.gonew file mode 100644index 0000000000..6fe649b3dc--- /dev/null+++ b/server/pkg/utils/crypto/test_init.go@@ -0,0 +1,14 @@+package crypto++import (+ sodium "github.com/GoKillers/libsodium-go/sodium"+ "sync"+)++var initOnce sync.Once++func InitSodiumForTest() {+ initOnce.Do(func() {+ sodium.Init()+ })+}\ No newline at end of file