libsodium_dart_bindings icon indicating copy to clipboard operation
libsodium_dart_bindings copied to clipboard

How does one use AES-GCM?

Open tomekit opened this issue 2 years ago • 12 comments

I've just realized that this package doesn't have API bindings to AES-GCM.

#/lib/src/api/aead.dart
/// Currently, only the crypto_aead_xchacha20poly1305_ietf_* APIs have been
/// implemented.

I've noticed relevant functions inside of: bindings/libsodium.ffi.dart, e.g. crypto_aead_aes256gcm_encrypt

Is there any shortcut I could perhaps use with FFI directly to call relevant libsodium functions and get the AES-GCM decrypt/encrypt? I need to say that I didn't have chance to work with FFI directly, but it seems now it is the moment.

Any hints are very much appreciated.

tomekit avatar Jan 24 '23 12:01 tomekit

It's probably terrible way of doing it, but I've copied the XChaCha20 wrappers, renamed them accordingly and it just started to work. It's just amazing.

Very experimental and not tested. https://github.com/Skycoder42/libsodium_dart_bindings/compare/main...tomekit:libsodium_dart_bindings:main

Example code:

test('libsodium', () async {
      final libsodium = DynamicLibrary.open('/usr/lib/x86_64-linux-gnu/libsodium.so'); // dpkg -L libsodium-dev | grep "\.so"
      final sodium = await SodiumInit.init(libsodium);
      // final SecureKey key = sodium.crypto.secretBox.keygen();

      final base64MasterKey = "+Hv/rT8HPG+Qmk3zhV2NDA==";
      final encryptedKey = "8IK5l6NGSudK/b57goLjZ6ePvfHj+w29D7rle8ShLCLdl0Yy5irmtw==";
      final cipherText = "CEs+CRiGBN/P9fANcqmHx4lnRd6wyj5ps2DoDDus9G7Cv+3FHqIy";
      final iv = "T4jMtxyX/+s60T3r";

      final unwrappedKey = AesKwRfc3394.unwrap(encryptedKey, base64MasterKey);

      final secureKey = SecureKey.fromList(sodium, Uint8List.fromList(unwrappedKey));

      final decryptedOutputBinary = sodium.crypto.aeadAes256Gcm.decrypt(cipherText: base64Decode(cipherText), nonce: base64Decode(iv), key: secureKey);

      final decryptedOutput = utf8.decode(decryptedOutputBinary);

      final expectedOutput = "encrypted_test_contents";
      assert(decryptedOutput == expectedOutput);
    });

tomekit avatar Jan 24 '23 12:01 tomekit

Generally speaking: Yes, use the FFI-API directly is the way to go. You also do not have to extend the library for that. You can directly instanciate a LibSodiumFFI simply by passing a DynamicLibrary object with the loaded libsodium binary to it.

However, I have been planning on adding the AES APIs for quite a while now. So maybe, If you create a PR, I can check if the code is OK and add the missing JS implementation.

Skycoder42 avatar Jan 25 '23 06:01 Skycoder42

I will be playing with Dart libsodium and AES-GCM over the next few days, so I will validate if things work OK. I will then create PR.

tomekit avatar Jan 25 '23 19:01 tomekit

I am trying to use stock: sodium_libs: ^2.0.0, but would like to import custom sodium (with experimental AES-GCM added), so I've added below override to dependency_overrides:

sodium:
    git:
      url: https://github.com/tomekit/libsodium_dart_bindings.git
      ref: main
      path: packages/sodium

however when trying to run my unit test, I am getting pretty long list of errors, some of them related to freezed and some annotation processing?

./../../.pub-cache/git/libsodium_dart_bindings-ad06e5f640970aa78adf8653b67245d958b07384/packages/sodium/lib/src/api/detached_cipher_result.dart:6:6: Error: Error when reading '../../../.pub-cache/git/libsodium_dart_bindings-ad06e5f640970aa78adf8653b67245d958b07384/packages/sodium/lib/src/api/detached_cipher_result.freezed.dart': No such file or directory
part 'detached_cipher_result.freezed.dart';

== UPDATE: As a temporary solution I've built these files using: flutter pub run build_runner build --delete-conflicting-outputs in sodium, and then committed these to different branch and then loaded from the pubspec.yaml

tomekit avatar Jan 25 '23 19:01 tomekit

Right, so it's not that easy. It seems that: swift-sodium doesn't support AES-GCM. https://github.com/jedisct1/swift-sodium

Invalid argument(s): Failed to lookup symbol 'crypto_aead_aes256gcm_abytes': dlsym(RTLD_DEFAULT, crypto_aead_aes256gcm_abytes): symbol not found

tomekit avatar Jan 26 '23 13:01 tomekit

Oh okay, that is a problem. Maybe you should open an issue over there to see if they can enable it? I guess they leave it out by default for size optimizations.

Skycoder42 avatar Jan 27 '23 06:01 Skycoder42

And regarding the freezed files: Yes, that is correct. The generated files are not checked in on purpose, thus the package is not usabled directly from git. Creating a seperate branch is fine. The other option would have been to check it out locally, generate the files and then add it as path dependency.

Skycoder42 avatar Jan 27 '23 06:01 Skycoder42

I didn't have time to investigate the issue exactly however it seems that actually both: sodium.crypto.aeadAes256Gcm.decrypt and sodium.crypto.aeadAes256Gcm.encrypt functions are failing on a real Android device with: "A low-level libsodium operation has failed", however they work fine on an Android emulator (E.g. Nexus 5 - API 31), as well as Linux and Windows. On Android I've replaced it with success using: https://github.com/hugo-pcl/native-crypto-flutter

Not an issue report really, but just a comment if someone would like to rely on this.

tomekit avatar Mar 09 '23 16:03 tomekit

This might have to do with how the native binaries are compiled. Generally, libsodium only includes AES for compatibility reasons, but does not "actively" support it. So I guess you are probably better off using a different library for that usecase anyways...

Skycoder42 avatar Mar 09 '23 16:03 Skycoder42

Right, so it's not that easy. It seems that: swift-sodium doesn't support AES-GCM. https://github.com/jedisct1/swift-sodium

Invalid argument(s): Failed to lookup symbol 'crypto_aead_aes256gcm_abytes': dlsym(RTLD_DEFAULT, crypto_aead_aes256gcm_abytes): symbol not found

FYI: The 2.1.0 release of sodium_libs now does not depend on swift-sodium anymore but instead directly include the native libsodium binaries. So at least on iOS/macOS, this problem might be fixed.

Skycoder42 avatar Apr 10 '23 09:04 Skycoder42

That's really great to hear. Is it possible by any chance that this change also resolves the: "A low-level libsodium operation has failed" for AES on a real Android device?

tomekit avatar Apr 10 '23 09:04 tomekit

No, I don't think so - the android build hasn't really changed. However, there problem there is not missing symbols, but some low level error. I already compile with all options enabled for android and use the official build scripts, so I don't think the issue is with the flutter bindings, but the C-library itself. You should open an issue at https://github.com/jedisct1/libsodium, maybe there you can find help with that problem.

Skycoder42 avatar Apr 10 '23 10:04 Skycoder42