π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add more tests
Neeraj Guptaa31e1f13595f
diff --git a/server/pkg/utils/crypto/crypto.go b/server/pkg/utils/crypto/crypto.goindex eb1b40e1f4..bbe575f373 100644--- a/server/pkg/utils/crypto/crypto.go+++ b/server/pkg/utils/crypto/crypto.go@@ -55,7 +55,16 @@ func GetHash(data string, hashKey []byte) (string, error) {if err != 0 {return "", stacktrace.NewError("email hash failed")}- return base64.StdEncoding.EncodeToString(dataHashBytes), nil+ result := base64.StdEncoding.EncodeToString(dataHashBytes)+ nativeResult, err2 := GetHashNative(data, hashKey)+ if err2 != nil {+ return "", stacktrace.Propagate(err2, "failed to get native hash")+ }+ if result != nativeResult {+ return "", stacktrace.NewError("hash mismatch between libsodium and native implementations")+ }+ return result, nil+}func GetEncryptedToken(token string, publicKey string) (string, error) {diff --git a/server/pkg/utils/crypto/crypto_native.go b/server/pkg/utils/crypto/crypto_native.goindex 085fbec06c..81c3feaf6c 100644--- a/server/pkg/utils/crypto/crypto_native.go+++ b/server/pkg/utils/crypto/crypto_native.go@@ -46,9 +46,6 @@ func encryptWithNonceNative(data string, encryptionKey []byte, nonce []byte) (en}func DecryptNative(cipher []byte, encryptionKey []byte, nonce []byte) (string, error) {- cipherBytes := cipher- nonceBytes := nonce-// Convert key to arrayif len(encryptionKey) != SecretBoxKeyBytes {return "", stacktrace.NewError("invalid key length")@@ -57,14 +54,14 @@ func DecryptNative(cipher []byte, encryptionKey []byte, nonce []byte) (string, ecopy(key[:], encryptionKey)// Convert nonce to array- if len(nonceBytes) != SecretBoxNonceBytes {+ if len(nonce) != SecretBoxNonceBytes {return "", stacktrace.NewError("invalid nonce length")}var nonceArray [SecretBoxNonceBytes]byte- copy(nonceArray[:], nonceBytes)+ copy(nonceArray[:], nonce)// Decrypt using secretbox- decrypted, ok := secretbox.Open(nil, cipherBytes, &nonceArray, &key)+ decrypted, ok := secretbox.Open(nil, cipher, &nonceArray, &key)if !ok {return "", stacktrace.NewError("decryption failed")}diff --git a/server/pkg/utils/crypto/sealed_box_deep_test.go b/server/pkg/utils/crypto/sealed_box_deep_test.gonew file mode 100644index 0000000000..1d03a2ff85--- /dev/null+++ b/server/pkg/utils/crypto/sealed_box_deep_test.go@@ -0,0 +1,109 @@+package crypto++import (+ "crypto/rand"+ "encoding/base64"+ "encoding/hex"+ "testing"++ "github.com/GoKillers/libsodium-go/cryptobox"+ generichash "github.com/GoKillers/libsodium-go/cryptogenerichash"+ "github.com/stretchr/testify/require"+ "golang.org/x/crypto/blake2b"+ "golang.org/x/crypto/nacl/box"+)++func TestNonceDerivationInDetail(t *testing.T) {+ // Initialize libsodium+ InitSodiumForTest()++ // Generate a test keypair+ recipientPublicKey, _, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)++ // Generate ephemeral keypair+ ephemeralPublicKey, _, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)++ t.Run("test_libsodium_nonce_derivation", func(t *testing.T) {+ // According to libsodium source, crypto_box_seal derives nonce as:+ // crypto_generichash(nonce, 24, ephemeral_pk || recipient_pk, 64, NULL, 0)+ // This is an UNKEYED hash of the concatenated public keys++ // Method 1: What our native code currently does (unkeyed hash)+ nonceInput := make([]byte, 64)+ copy(nonceInput[:32], ephemeralPublicKey[:])+ copy(nonceInput[32:], recipientPublicKey[:])++ hash1, err := blake2b.New(24, nil) // unkeyed+ require.NoError(t, err)+ hash1.Write(nonceInput)+ nonce1 := hash1.Sum(nil)++ // Method 2: What the comment suggests (keyed hash - INCORRECT)+ // crypto_generichash(nonce, 24, recipient_pk, 32, ephemeral_pk, 32)+ // This would be recipient_pk as message, ephemeral_pk as key+ hash2, err := blake2b.New(24, ephemeralPublicKey[:])+ require.NoError(t, err)+ hash2.Write(recipientPublicKey[:])+ nonce2 := hash2.Sum(nil)++ // Method 3: Using libsodium's generic hash to verify+ // This should match Method 1 if our understanding is correct+ nonce3, errCode := generichash.CryptoGenericHash(24, nonceInput, nil)+ require.Equal(t, 0, errCode)++ t.Logf("Method 1 (native - unkeyed): %s", hex.EncodeToString(nonce1))+ t.Logf("Method 2 (keyed - wrong): %s", hex.EncodeToString(nonce2))+ t.Logf("Method 3 (libsodium): %s", hex.EncodeToString(nonce3))++ // The correct implementation should match libsodium+ require.Equal(t, nonce3, nonce1, "Native implementation should match libsodium's nonce derivation")+ require.NotEqual(t, nonce2, nonce3, "Keyed hash should NOT match (proving the comment is incorrect)")+ })++ t.Run("actual_interop_test", func(t *testing.T) {+ // Let's do a real interop test with fixed keys to be absolutely sure+ // Generate a fixed recipient keypair for reproducible testing+ var fixedRecipientPubKey [32]byte+ var fixedRecipientPrivKey [32]byte+ for i := range fixedRecipientPubKey {+ fixedRecipientPubKey[i] = byte(i)+ fixedRecipientPrivKey[i] = byte(255 - i)+ }++ // Actually generate a valid keypair+ realPubKey, realPrivKey, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)++ message := []byte("test message for sealed box")++ // Encrypt with libsodium+ sealed, errCode := cryptobox.CryptoBoxSeal(message, realPubKey[:])+ require.Equal(t, 0, errCode, "libsodium seal should work")++ // Decrypt with libsodium to verify it works+ unsealed, errCode := cryptobox.CryptoBoxSealOpen(sealed, realPubKey[:], realPrivKey[:])+ require.Equal(t, 0, errCode, "libsodium unseal should work")+ require.Equal(t, message, unsealed, "round trip should work")++ // Now test with our functions+ token := base64.URLEncoding.EncodeToString(message)+ pubKeyB64 := base64.StdEncoding.EncodeToString(realPubKey[:])++ encrypted, err := GetEncryptedTokenNative(token, pubKeyB64)+ require.NoError(t, err)++ encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)+ require.NoError(t, err)++ // Try to decrypt with libsodium+ decrypted, errCode := cryptobox.CryptoBoxSealOpen(encryptedBytes, realPubKey[:], realPrivKey[:])+ if errCode != 0 {+ t.Errorf("FAILED: libsodium cannot decrypt native sealed box")+ } else {+ require.Equal(t, message, decrypted, "Decryption should produce original message")+ t.Log("SUCCESS: Native sealed box is compatible with libsodium")+ }+ })+}\ No newline at end of filediff --git a/server/pkg/utils/crypto/sealed_box_test.go b/server/pkg/utils/crypto/sealed_box_test.gonew file mode 100644index 0000000000..6c647d2828--- /dev/null+++ b/server/pkg/utils/crypto/sealed_box_test.go@@ -0,0 +1,74 @@+package crypto++import (+ "crypto/rand"+ "encoding/base64"+ "testing"++ "github.com/GoKillers/libsodium-go/cryptobox"+ "github.com/stretchr/testify/require"+ "golang.org/x/crypto/nacl/box"+)++func TestSealedBoxCompatibility(t *testing.T) {+ // Initialize libsodium+ InitSodiumForTest()++ // Generate a test keypair for the recipient+ recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err, "should generate keypair")++ // Prepare test data+ originalToken := "test-token-12345"+ tokenBytes := []byte(originalToken)+ publicKeyBase64 := base64.StdEncoding.EncodeToString(recipientPublicKey[:])+ tokenBase64 := base64.URLEncoding.EncodeToString(tokenBytes)++ t.Run("libsodium sealed box can be opened", func(t *testing.T) {+ // Encrypt with libsodium's crypto_box_seal+ encryptedLibsodium, errCode := cryptobox.CryptoBoxSeal(tokenBytes, recipientPublicKey[:])+ require.Equal(t, 0, errCode, "libsodium encryption should succeed")++ // Try to open with libsodium's crypto_box_seal_open+ decrypted, errCode := cryptobox.CryptoBoxSealOpen(encryptedLibsodium, recipientPublicKey[:], recipientPrivateKey[:])+ require.Equal(t, 0, errCode, "libsodium should decrypt its own sealed box")+ require.Equal(t, tokenBytes, decrypted, "decrypted should match original")+ })++ t.Run("compare GetEncryptedToken with GetEncryptedTokenNative", func(t *testing.T) {+ // Encrypt with both implementations+ encryptedLibsodium, err := GetEncryptedToken(tokenBase64, publicKeyBase64)+ require.NoError(t, err, "libsodium GetEncryptedToken should succeed")++ encryptedNative, err := GetEncryptedTokenNative(tokenBase64, publicKeyBase64)+ require.NoError(t, err, "native GetEncryptedTokenNative should succeed")++ // Decode the encrypted data+ encryptedLibsodiumBytes, err := base64.StdEncoding.DecodeString(encryptedLibsodium)+ require.NoError(t, err)++ encryptedNativeBytes, err := base64.StdEncoding.DecodeString(encryptedNative)+ require.NoError(t, err)++ // Both should be 48 bytes + len(tokenBytes) (32 bytes ephemeral pubkey + 16 bytes auth tag + message)+ expectedLen := 32 + 16 + len(tokenBytes)+ require.Equal(t, expectedLen, len(encryptedLibsodiumBytes), "libsodium sealed box should have correct length")+ require.Equal(t, expectedLen, len(encryptedNativeBytes), "native sealed box should have correct length")++ // Try to decrypt libsodium's output with libsodium+ decryptedLib, errCode := cryptobox.CryptoBoxSealOpen(encryptedLibsodiumBytes, recipientPublicKey[:], recipientPrivateKey[:])+ require.Equal(t, 0, errCode, "libsodium should decrypt its own output")+ require.Equal(t, tokenBytes, decryptedLib, "libsodium decrypted should match original")++ // CRITICAL TEST: Try to decrypt native's output with libsodium+ decryptedNative, errCode := cryptobox.CryptoBoxSealOpen(encryptedNativeBytes, recipientPublicKey[:], recipientPrivateKey[:])+ if errCode != 0 {+ t.Errorf("COMPATIBILITY ISSUE: libsodium cannot decrypt native sealed box (error code: %d)", errCode)+ t.Log("This confirms the nonce derivation is incompatible")+ } else {+ require.Equal(t, tokenBytes, decryptedNative, "cross-decryption should work if compatible")+ t.Log("SUCCESS: Native implementation is compatible with libsodium")+ }+ })++}