firstfloorsoftware / flutter_sodium Goto Github PK
View Code? Open in Web Editor NEWFlutter bindings for libsodium
License: BSD 3-Clause "New" or "Revised" License
Flutter bindings for libsodium
License: BSD 3-Clause "New" or "Revised" License
#7 is already open and has a list of missing APIs but is marked as Android only.
Any functions returning a map would be better off returning an object with members. As it stands, the developer needs to figure out that the public key and secret key are returned under the keys 'pk' and 'sk', and perform their own check that those parameters are actually returned.
At the least the map should be documented and there should be constants for the various keys.
If this were to be changed it is a breaking change, but one that could be mitigated either completely or partially by making the class being returned either implement Map<String,Uint8List>
or at least override operator [](String key)
.
The same goes for the functions that reutrn tx/rx keys and nonce+encrypted key or key+nonce.
Hey @kozw, firstly thank you so much for the great work.
I'm running into issues while trying to decrypt a large file that was encrypted with Xchacha20poly1305
.
This is how I'm encrypting the file:
final key = Sodium.cryptoSecretstreamXchacha20poly1305Keygen();
final chunkSize = 4 * 1024 * 1024; // 4 MB
final initPushResult = Sodium.cryptoSecretstreamXchacha20poly1305InitPush(key);
var bytesRead = 0;
var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
var bufferLength = chunkSize;
if (bytesRead + bufferLength >= inputFileLength) { // Last block
bufferLength = inputFileLength - bytesRead;
tag = Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
}
final buffer = await inputFile.read(bufferLength);
bytesRead += bufferLength;
final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
initPushResult.state, buffer, null, tag);
outputFile.writeFromSync(encryptedData);
}
This is how I'm decrypting the file:
final chunkSize = (4 * 1024 * 1024) + Sodium.cryptoSecretstreamXchacha20poly1305Abytes;
final pullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
initPushResult.header, key);
var bytesRead = 0;
var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
var bufferLength = chunkSize;
if (bytesRead + bufferLength >= inputFileLength) { // Last block
bufferLength = inputFileLength - bytesRead;
}
final buffer = await inputFile.read(bufferLength);
bytesRead += bufferLength;
final pullResult = Sodium.cryptoSecretstreamXchacha20poly1305Pull(
pullState, buffer, null);
outputFile.writeFromSync(pullResult.m);
tag = pullResult.tag;
}
Here the decryption "pull" fails with the following error:
crypto_secretstream_xchacha20poly1305_pull failed with -1
As per the documentation, this means that the ciphertext is invalid.
But I'm not sure what is amiss here. Would be great if you could help out. Thank you!
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':app:preDebugBuild'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
> Could not resolve com.github.joshjdevl.libsodiumjni:libsodium-jni-aar:2.0.2-SNAPSHOT.
Required by:
project :app > project :flutter_sodium
> Could not resolve com.github.joshjdevl.libsodiumjni:libsodium-jni-aar:2.0.2-SNAPSHOT.
> Unable to load Maven meta-data from https://oss.sonatype.org/content/repositories/snapshots/com/github/joshjdevl/libsodiumjni/libsodium-jni-aar/2.0.2-SNAPSHOT/maven-metadata.xml.
> Could not HEAD 'https://oss.sonatype.org/content/repositories/snapshots/com/github/joshjdevl/libsodiumjni/libsodium-jni-aar/2.0.2-SNAPSHOT/maven-metadata.xml'. Received status code 503 from server: Service Temporarily Unavailable
Should be better to use this maven url https://mvnrepository.com/artifact/com.github.joshjdevl.libsodiumjni/libsodium-jni-aar
Hi @kozw I'm curious if there is or was a reason why KeyDerivation.deriveFromKey(masterKey, subKeyId, subKeyLength) implicitly differs from Sodium.cryptoKdfDeriveFromKey(subKeyLength, subKeyId, context, masterKey) ?
This plugin currently ignores user-defined context by using hard-coded String context = '00000000'
Also, for consistency, why not follow the same input structure as Sodium.cryptoKdfDeriveFromKey(subKeyLength, subKeyId, context, masterKey) ?
https://github.com/firstfloorsoftware/flutter_sodium/blob/master/lib/src/key_derivation.dart
The ultimate goal is to provide 100% coverage of the libsodium API in flutter. Not there yet, tracking progress of the entire libsodium API (725 symbols) in this issue.
Send PR or drop a note if you need to access a particular API not covered yet.
I'm receiving the following error: MissingPluginException(No implementation found for method crypto_box_keypair on channel flutter_sodium)
I've tried reloads, restarts, starting a new project with JUST the offending code, deleting generated files and rebuilding, nothing works. Code below.
Example class:
import 'package:flutter_sodium/flutter_sodium.dart';
class KeygenTest {
KeygenTest();
Future<String> generateKeys () async {
KeyPair keys = await CryptoBox.generateKeyPair();
print (keys.toString());
return "generated";
}
}
Unit test:
import 'package:flutter_test/flutter_test.dart';
import 'keygen.dart';
void main() {
group("keygen", () {
test("generate key", () async {
KeygenTest test = new KeygenTest();
await test.generateKeys();
});
});
}
Full output:
$ flutter test lib/keygen.test.dart
00:12 +0 -1: keygen generate key [E]
MissingPluginException(No implementation found for method crypto_box_keypair on channel flutter_sodium)
package:flutter/src/services/platform_channel.dart 278:7 MethodChannel.invokeMethod
===== asynchronous gap ===========================
dart:async _AsyncAwaitCompleter.completeError
package:flutter/src/services/platform_channel.dart MethodChannel.invokeMethod
===== asynchronous gap ===========================
dart:async _asyncThenWrapperHelper
package:flutter/src/services/platform_channel.dart MethodChannel.invokeMethod
package:flutter_sodium/flutter_sodium.dart 554:10 Sodium.cryptoBoxKeypair
I'm using Flutter_Sodium version 0.2.0 and tried to generate an Argon2id13 password hash using the sensitive parameter set.
My system parameter were:
Flutter 2.2.1
Dart 2.13.1
Sodium version: 1.0.18
Android 11: sdk_gphone_x86_arm-userdebug 11 RSR1.201013.001 6903271 dev-keys
This is the code I used to generate the hash (the full code follows at the end):
printC('Generate a 32 byte long encryption key with Argon2id in sensitive mode');
printC('Sodium version: ' + Sodium.versionString);
printC('Dart version: ' + Platform.version);
final passphrase = 'secret passphrase';
printC('passphrase: ' + passphrase);
var salt16Byte = generateSalt16Byte();
printC('salt (Base64): ' + base64Encoding(salt16Byte));
final outlen = 32;
final passwd = utf8.encoder.convert(passphrase);
final opslimit = Sodium.cryptoPwhashOpslimitSensitive;
final memlimit = Sodium.cryptoPwhashMemlimitSensitive;
final alg = Sodium.cryptoPwhashAlgArgon2id13;
printC('opsLimit: ' + Sodium.cryptoPwhashOpslimitSensitive.toString());
printC('memLimit: ' + Sodium.cryptoPwhashMemlimitSensitive.toString());
final hash =
Sodium.cryptoPwhash(outlen, passwd, salt16Byte, opslimit, memlimit, alg);
printC('hash (Base64): ' + base64Encoding(hash));
I'm using the constants Sodium.cryptoPwhashOpslimitSensitive and Sodium.cryptoPwhashMemlimitSensitive for opsLimit and memLimit.
The code fails with an Exception caught by gesture: SodiumException crypto_pwhash failed with -1 (full stack see below:):
I/flutter ( 9661): Generate a 32 byte long encryption key with Argon2id in sensitive mode
I/flutter ( 9661): Sodium version: 1.0.18
I/flutter ( 9661): Dart version: 2.13.1 (stable) (Fri May 21 12:45:36 2021 +0200) on "android_ia32"
I/flutter ( 9661): passphrase: secret passphrase
I/flutter ( 9661): salt (Base64): tVcZQuWbpNxGrvJ45H5Q8Q==
I/flutter ( 9661): opsLimit: 4
I/flutter ( 9661): memLimit: 1073741824
======== Exception caught by gesture ===============================================================
The following SodiumException object was thrown while handling a gesture:
crypto_pwhash failed with -1
When the exception was thrown, this was the stack:
#0 Result.mustSucceed (package:flutter_sodium/src/extensions.dart:48:7)
#1 Sodium.cryptoPwhash (package:flutter_sodium/src/sodium.dart:1087:12)
#2 _MyWidgetState.runYourMainDartCode (package:dartprojectspointycastle/CrossPlatformCryptography/LibsodiumArgon2idSensitiveIssue.dart:136:12)
#3 _MyWidgetState.build.<anonymous closure> (package:dartprojectspointycastle/CrossPlatformCryptography/LibsodiumArgon2idSensitiveIssue.dart:82:21)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#87d41
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(300.3, 727.6)
finalLocalPosition: Offset(35.2, 10.3)
button: 1
sent tap down
====================================================================================================
full code (it's a simple console app, just press "run the code"):
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_sodium/flutter_sodium.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Console'),
),
body: MyWidget(),
),
);
}
}
// widget class
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
// state variable
String _textString = 'press the button "run the code"';
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(
'console output',
style: TextStyle(fontSize: 30),
),
Expanded(
flex: 1,
child: new SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
child: Text(_textString,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
fontFamily: 'Courier',
color: Colors.black,
))),
),
),
Container(
child: Row(
children: <Widget>[
SizedBox(width: 10),
Expanded(
child: ElevatedButton(
child: Text('clear console'),
onPressed: () {
clearConsole();
},
),
),
SizedBox(width: 10),
Expanded(
child: ElevatedButton(
child: Text('extra Button'),
onPressed: () {
runYourSecondDartCode();
},
),
),
SizedBox(width: 10),
Expanded(
child: ElevatedButton(
child: Text('run the code'),
onPressed: () {
runYourMainDartCode();
},
),
),
SizedBox(width: 10),
],
),
),
],
);
}
void clearConsole() {
setState(() {
_textString = ''; // will add additional lines
});
}
void printC(_newString) {
setState(() {
_textString =
_textString + _newString + '\n';
});
print(_newString); // extra output on Console
}
/* ### instructions ###
place your code inside runYourMainDartCode and print it to the console
using printC('your output to the console');
clearConsole() clears the actual console
place your code that needs to be executed additionally inside
runYourSecondDartCode and start it with "extra Button"
*/
void runYourMainDartCode() {
clearConsole();
printC('Generate a 32 byte long encryption key with Argon2id in sensitive mode');
printC('Sodium version: ' + Sodium.versionString);
printC('Dart version: ' + Platform.version);
final passphrase = 'secret passphrase';
printC('passphrase: ' + passphrase);
var salt16Byte = generateSalt16Byte();
printC('salt (Base64): ' + base64Encoding(salt16Byte));
final outlen = 32;
final passwd = utf8.encoder.convert(passphrase);
final opslimit = Sodium.cryptoPwhashOpslimitSensitive;
final memlimit = Sodium.cryptoPwhashMemlimitSensitive;
final alg = Sodium.cryptoPwhashAlgArgon2id13;
printC('opsLimit: ' + Sodium.cryptoPwhashOpslimitSensitive.toString());
printC('memLimit: ' + Sodium.cryptoPwhashMemlimitSensitive.toString());
final hash =
Sodium.cryptoPwhash(outlen, passwd, salt16Byte, opslimit, memlimit, alg);
printC('hash (Base64): ' + base64Encoding(hash));
}
Uint8List generateSalt16Byte() {
return Sodium.randombytesBuf(16);
}
String base64Encoding(Uint8List input) {
return base64.encode(input);
}
void runYourSecondDartCode() {
printC('execute additional code');
}
}
The Flutter 2019 roadmap lists better support for C/C++ libraries from Flutter, including direct calls to C/C++ from Dart. This is of major importance for flutter_sodium. The current implementation uses platform channels with Java and Swift interop.
Not only is the runtime performance sub-optimal, there's a lot of code to write and maintain. Not to mention the fact that the Android version is still lacking in features compared to iOS due to a dependency on incomplete 3rd party libraries (#7)
As soon as native C interop is available, flutter_sodium should take advantage of it. You can track the Dart issue and read more in the FFI vision document. Looks like an initial version is planned somewhere in Q1 2019.
Some public facing classes are missing API documentation
[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: Invalid argument(s): Failed to lookup symbol (dlsym(RTLD_DEFAULT, crypto_box_seedbytes): symbol not found)
#0 DynamicLibrary.lookup (dart:ffi-patch/ffi_dynamic_library_patch.dart:31:29)
#1 Bindings.lookupSizet (package:flutter_sodium/src/bindings/libsodium.dart:29:14)
#2 new CryptoBoxBindings (package:flutter_sodium/src/bindings/crypto_box_bindings.dart:9:17)
#3 Sodium._cryptoBox (package:flutter_sodium/src/sodium.dart:35:29)
#4 Sodium._cryptoBox (package:flutter_sodium/src/sodium.dart)
#5 Sodium.cryptoBoxPublickeybytes (package:flutter_sodium/src/sodium.dart:190:7)
#6 Sodium.cryptoBoxKeypair (package:flutter_sodium/src/sodium.dart:226:40)
#7 CryptoBox.randomKeys (package:flutter_sodium/src/crypto_box.dart:10:41)
#8 generateKeys (package:vlow/screens/onboarding_screen.dart:171:36)
#9 _OnboardingState.create (package:vlow/screens/onboarding_screen.dart:47:28)
#10 GestureRecognizer.invokeCallbac<โฆ>
Flutter (Channel stable, 1.20.2, on Mac OS X 10.15.6 19G73, locale en-GB)
=== BUILD TARGET flutter_sodium OF PROJECT Pods WITH CONFIGURATION Debug ===
warning: no rule to process file '/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.2/ios/Classes/libsodium-ios/lib/libsodium.a' of type archive.ar for architecture armv7
warning: no rule to process file /.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.2/ios/Classes/libsodium-ios/lib/libsodium.a' of type archive.ar for architecture arm64
/Users/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.2/ios/Classes/FlutterSodiumPlugin.m:2:9: fatal error: 'flutter_sodium/flutter_sodium-Swift.h' file not found
#import <flutter_sodium/flutter_sodium-Swift.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
Since the newest update, I get an error when running my project:
Invalid plugin specification flutter_sodium.
Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. An instruction to format the `pubspec.yaml` can be found here: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms
Has someone found a bugfix for that?
I found a similar error in another package (simolus3/drift#727 (comment)) but I can't adapt the changes to this project.
IMPORTANT NOTE
I'm currently porting flutter_sodium to FFI. The goal is to achieve 100% API coverage with FFI. The platform channel implementation is still maintained, but there are no plans to fix the missing APIs.
Several APIs are not available on Android. This is the complete list of libsodiumjni APIs that are missing or malfunctioning:
This is a bit of a strange issue. I'm not getting an error, or any kind of response from the function what so ever. It just does nothing. The following code is what I'm using to call the function. The execution just stops when the function is called although my flutter app continues to operate.
var encoder = new JsonEncoder();
var jsonencoded = encoder.convert(data);
var jsonBeforeSeal = utf8.encode(jsonencoded);
print("Data before seal.");
print(jsonBeforeSeal);
print("Public Key");
print(_publicKey);
Uint8List response = await Sodium.cryptoBoxSeal(jsonBeforeSeal, utf8.encode(_publicKey));
The public key is returned from my server in hex format and worked in my ionic version of my app.
Review and fix gitignore to ensure local source files do not end up in the repo.
Thank you very much for the package for flutter and I appreciate all the work!.
I am currently trying to implement signal protocol with this package into my app using flutter.
I can create curve25519 pairs, generate the ed25519 for signing.
I noticed there is already a way to convert the ed25519 into a curve25519(secret key only)
I also noticed, when we convert the secret ed25519 into curve25519, it always results in the same output(when the ed25519 is static). Wonderful i guess.
On to the issue/request
If we can be allowed to convert the ed25519(public key) into a curve25519. That would be great.
but i have a question, can the converted ed25519(public key) be used for encryption and the converted ed25519(secret key) be used for decryption.
I mean, when we convert both secret and public keys into curve25519, are they a match as pairs? which can be used to come to a shared secret against a different unique pair?
I want to utilize the ed25519 which I can convert to curve25519 for my Identity pair and also use it for signing.
Thank you!
Please upgrade to ffi ^2.0.1 as I am unable to update other packages that have moved on to ffi 2.0.1
Thanks for putting together this package.
Is there anyway to get access to libsodiums XChaCha20-Poly1305-IETF?
Bug on nexus 5 Android v5.1.1:
W/linker ( 7315): libflutter.so: unused DT entry: type 0x6ffffef5 arg 0x1ec18
W/linker ( 7315): libflutter.so: unused DT entry: type 0x6ffffffe arg 0x1ebb8
W/linker ( 7315): libflutter.so: unused DT entry: type 0x6fffffff arg 0x3
hi, i do have a hard time resolving this issue:
$ git clone https://github.com/firstfloorsoftware/flutter_sodium.git
$ cd ./flutter_sodium/
$ flutter pub get
$ cd ./example
$ flutter run
Launching lib/main.dart on u2nite in debug mode...
Updating minimum iOS deployment target from 8.0 to 9.0.
Upgrading project.pbxproj
Upgrading AppFrameworkInfo.plist
Running pod install... 1,224ms
Running Xcode build...
Xcode build done. 2.7s
Failed to build iOS app
Error output from Xcode build:
โณ
** BUILD FAILED **
Xcode's output:
โณ
ld: in
/tmp/flutter_sodium/example/ios/Pods/../.symlinks/plugins/flutter_sodium/ios/libsodium
.a(libsodium_la-aead_chacha20poly1305.o), building for iOS Simulator, but linking in
object file built for iOS, file
'/tmp/flutter_sodium/example/ios/Pods/../.symlinks/plugins/flutter_sodium/ios/libsodiu
m.a' for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
note: Using new build system
note: Building targets in parallel
note: Planning build
note: Analyzing workspace
note: Constructing build description
note: Build preparation complete
/tmp/flutter_sodium/example/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator
deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of
supported deployment target versions is 9.0 to 14.5.99. (in target 'Flutter' from
project 'Pods')
Could not build the application for the simulator.
Error launching application on simulator.
strange enough, building and running the example app works when using xcode
$ open ios/Runner.xcworkspace/
my env:
$ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[โ] Flutter (Channel beta, 2.4.0-4.2.pre, on macOS 11.4 20F71 darwin-x64, locale en-US)
[โ] Android toolchain - develop for Android devices (Android SDK version 31.0.0-rc3)
[โ] Xcode - develop for iOS and macOS
[โ] Chrome - develop for the web
[โ] Android Studio (version 4.2)
[โ] VS Code (version 1.58.2)
[โ] Connected device (3 available)
....
โข No issues found!
Any suggestions?
Hello!
Looks like flutter_sodium is not providing a minimum api version, so it adds android.permission.READ_PHONE_STATE implicitly to the build bundle\apk:
uses-permission#android.permission.READ_PHONE_STATE
IMPLIED from AndroidManifest.xml reason: com.firstfloorsoftware.flutter_sodium has a targetSdkVersion < 4
Docs:
https://developer.android.com/reference/android/Manifest.permission.html#READ_PHONE_STATE
READ_PHONE_STATE
Allows read only access to phone state, including the phone number of the device, current cellular network information, the status of any ongoing calls, and a list of any PhoneAccounts registered on the device.Note: If both your minSdkVersion and targetSdkVersion values are set to 3 or lower, the system implicitly grants your app this permission. If you don't need this permission, be sure your targetSdkVersion is 4 or higher.
Would be nice if flutter_sodium may provide minSdkVersion or targetSdkVersion to avoid this permission, because it is about sensitive user data which is not used by our app.
Thank you :)
It would be really nice if Flutter web could be supported by using platform channels and one of the js libraries available.
First I'd like to thank you for all your hard work. I really love your project and without it the Psono app would not be possible!
Now to the problem. I have recently upgraded gradle and so on yet now I receive this error:
FAILURE: Build failed with an exception.
* Where:
Build file '/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.1.9/android/build.gradle' line: 1
* What went wrong:
A problem occurred evaluating root project 'flutter_sodium'.
> Plugin with id 'com.android.library' not found.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 9s
The plugin flutter_sodium could not be built due to the issue above.
Googling it brought be to this stackoverflow article.
Which blames this line here https://github.com/firstfloorsoftware/flutter_sodium/blob/master/android/build.gradle#L1
I downgraded again to com.android.tools.build:gradle:3.6.4
and things are working again.
Created a new Flutter project with -i swift -a kotlin
options, added flutter_sodium: ^0.0.9
to pubspec.yaml.
During debug build, I get the following errors:
Launching lib/main.dart on iPhone Xส in debug mode...
Xcode build done. 3.1s
Failed to build iOS app
Error output from Xcode build:
โณ
** BUILD FAILED **
Xcode's output:
โณ
=== BUILD TARGET flutter_sodium OF PROJECT Pods WITH CONFIGURATION Debug ===
warning: no rule to process file '~/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.9/ios/Classes/libsodium-ios/lib/libsodium.a' of type archive.ar for architecture x86_64
=== BUILD TARGET flutter_sodium OF PROJECT Pods WITH CONFIGURATION Debug ===
~/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.9/ios/Classes/SwiftFlutterSodiumPlugin.swift:1358:50: error: cannot convert value of type 'UnsafeMutablePointer<_>' to expected argument type 'OpaquePointer?'
flutter_sodium.crypto_generichash_init(statePtr, keyPtr, key.count, outlen)
^~~~~~~~
~/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.9/ios/Classes/SwiftFlutterSodiumPlugin.swift:1364:48: error: cannot convert value of type 'UnsafeMutablePointer<_>' to expected argument type 'OpaquePointer?'
flutter_sodium.crypto_generichash_init(statePtr, nil, 0, outlen)
^~~~~~~~
~/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.9/ios/Classes/SwiftFlutterSodiumPlugin.swift:1378:50: error: cannot convert value of type 'UnsafeMutablePointer<_>' to expected argument type 'OpaquePointer?'
flutter_sodium.crypto_generichash_update(statePtr, iPtr, CUnsignedLongLong(i.count))
^~~~~~~~
~/.pub-cache/hosted/pub.dartlang.org/flutter_sodium-0.0.9/ios/Classes/SwiftFlutterSodiumPlugin.swift:1394:49: error: cannot convert value of type 'UnsafeMutablePointer<_>' to expected argument type 'OpaquePointer?'
flutter_sodium.crypto_generichash_final(statePtr, outPtr, outlen)
^~~~~~~~
Could not build the application for the simulator.
Error launching application on iPhone Xส.
Exited (sigterm)
$ flutter doctor
[โ] Flutter (Channel stable, v1.2.1, on Mac OS X 10.14.4 18E226, locale en-US)
[โ] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[โ] iOS toolchain - develop for iOS devices (Xcode 10.2)
[โ] Android Studio (version 3.3)
[โ] VS Code (version 1.33.1)
[โ] Connected device (1 available)
โข No issues found!
Podfile
# Uncomment this line to define a global platform for your project
platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def parse_KV_file(file, separator='=')
file_abs_path = File.expand_path(file)
if !File.exists? file_abs_path
return [];
end
pods_ary = []
skip_line_start_symbols = ["#", "/"]
File.foreach(file_abs_path) { |line|
next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
plugin = line.split(pattern=separator)
if plugin.length == 2
podname = plugin[0].strip()
path = plugin[1].strip()
podpath = File.expand_path("#{path}", file_abs_path)
pods_ary.push({:name => podname, :path => podpath});
else
puts "Invalid plugin specification: #{line}"
end
}
return pods_ary
end
target 'Runner' do
use_frameworks!
# Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
# referring to absolute paths on developers' machines.
system('rm -rf .symlinks')
system('mkdir -p .symlinks/plugins')
# Flutter Pods
generated_xcode_build_settings = parse_KV_file('./Flutter/Generated.xcconfig')
if generated_xcode_build_settings.empty?
puts "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first."
end
generated_xcode_build_settings.map { |p|
if p[:name] == 'FLUTTER_FRAMEWORK_DIR'
symlink = File.join('.symlinks', 'flutter')
File.symlink(File.dirname(p[:path]), symlink)
pod 'Flutter', :path => File.join(symlink, File.basename(p[:path]))
end
}
# Plugin Pods
plugin_pods = parse_KV_file('../.flutter-plugins')
plugin_pods.map { |p|
symlink = File.join('.symlinks', 'plugins', p[:name])
File.symlink(p[:path], symlink)
pod p[:name], :path => File.join(symlink, 'ios')
}
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
config.build_settings['SWIFT_VERSION'] = '4.2'
end
end
end
Hi guys!
I recently moved an app to Flutter 2.x, and with that updated the flutter_sodium to the most up-to-date version.
After the update I started getting an RangeError coming from the library. Following the functions' calls I faced what I believe to be the issue. Just to clarify, here is the step-by-step:
KeyDerivation.derive
(src/key_derivation.dart) -> cryptoKdfDeriveFromKey
(src/sodium.dart) -> RangeError.checkValueInInterval(subkeyId, 0, (2 ^ 64) - 1, 'subkeyId')
The code checks here if subkeyId
fit in the interval between 0
and (2 ^ 64) - 1
.
Something was off about this error, so I made some research and concluded it's a typo in the max value of the range, probably came from the official sodium key derivation docs or something like that. In this page we have the identical math operation: subkey_id can be any value up to (2^64)-1
.
Apparently the end of the interval is erroneous represented here using the math notation instead of dart language notation, which means the ^
character is a bitwise XOR instead of the math operation power
, which I suppose should be the correct thing to do here. Btw, the result of (2 ^ 64) - 1
is always 65
.
Anyway, here is the issue. Can you guys confirm? I hope I'm not being blind about something and opening an issue with no need.
I have this error on Nexus 5 Android v5.1.1. Someone can help me on this ?
I/org.libsodium.jni.NaCl(13188): librarypath=/vendor/lib:/system/lib
W/linker (13188): libsodiumjni.so: unused DT entry: type 0x6ffffffe arg 0xf8ac
W/linker (13188): libsodiumjni.so: unused DT entry: type 0x6fffffff arg 0x2
can't build release apk, cause the issue:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':flutter_sodium:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> Android resource linking failed
C:\Users\thomasr\.gradle\caches\transforms-2\files-2.1\0a271e99b6771ad4a84318244d532fb7\core-1.0.0\res\values\values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.
C:\Users\thomasr\.gradle\caches\transforms-2\files-2.1\0a271e99b6771ad4a84318244d532fb7\core-1.0.0\res\values\values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.
Hi,
Included example app crashes on iOS:
Jun 16 13:48:42 iPhone-7 Runner(Flutter)[510] : [VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: Invalid argument(s): Failed to lookup symbol (dlsym(RTLD_DEFAULT, sodium_init): symbol not found)
#0 DynamicLibrary.lookup (dart:ffi-patch/ffi_dynamic_library_patch.dart:31)
#1 new SodiumBindings (package:flutter_sodium/src/bindings/sodium_bindings.dart:9)
#2 Sodium._sodium (package:flutter_sodium/src/sodium.dart:49)
#3 Sodium._sodium (package:flutter_sodium/src/sodium.dart:0)
#4 Sodium.sodiumInit (package:flutter_sodium/src/sodium.dart:2013)
#5 main (package:flutter_sodium_example/main.dart:7)
#6 _runMainZoned.. (dart:ui/hooks.dart:247)
#7 _rootRun (dart:async/zone.dart:1190)
#8 _CustomZone.run (dart:async/zone.dart:1093)
#9 _runZoned (dart:async/zone.dart:1630)
#10 runZonedGuarded (dart:async/zone.dart:1618)
#11 _runMainZoned. (dart:ui/hooks.dart:239)
#12 _startIsolate. (dart:isolate-patch/isolate_patch.dart:<\M-b\M^@\M-&>
Flutter 1.19.0-4.1.pre โข channel beta โข https://github.com/flutter/flutter.gitFramework โข revision f994b76974 (7 days ago) โข 2020-06-09 15:53:13 -0700Engine โข revision 9a28c3bcf4Tools โข Dart 2.9.0 (build 2.9.0-14.1.beta)
With Flutter is possible to read and write files through streams, this is very good if you have to do operations on large files because it's not necessary to store the entire file on the memory (also very limited on mobile devices).
It's possible with this library, even in theory, to decrypt and encrypt files with stream?
Hi, we've tried to use SealedBox.sealOpen(cipher, keyPair)
, but Unfortunately we faced an exception.
I checked the implementation and I realized you are forcing it to decode as UTF-8, and I think as we working with keys, and there are no special characters, and it is okay to decode it as ASCII.
I had to copy your code and change it to solve my issue.
UTF-8 decode should be optional.
Thanks
When I call cryptoPwhashStr
, the resulting output seems to always be of length 128 and is returned padded with \u000
s.
I don't see this behavior documented. All I can find is:
out must be large enough to hold crypto_pwhash_STRBYTES bytes, but the actual output string may be shorter.
Which makes me wonder if this check is necessary.
This extra padding seems to be breaking counterparts like libsodium.js which rejects calls to crypto_pwhash_str_verify
for hashes that are generated from the flutter_sodium library. Everything works fine if I trim out all but the last \u000
.
Apologies if I've missed something here. If I haven't, it would be great if we could have consistency across the multiple implementations of libsodium.
Thanks again for everything!
I get this issue.
pubspec.yaml
flutter_sodium: any
This is what I get when I open the android project and try to sync, the Same issue with fluter run.
ERROR: Failed to resolve: com.github.joshjdevl.libsodiumjni:libsodium-jni-aar:2.0.2-SNAPSHOT
Show in Project Structure dialog
Affected Modules: flutter_sodium
$ flutter test
00:11 +1 -1: Unlock FundRaiser Identity [E]
MissingPluginException(No implementation found for method crypto_sign_seed_keypair on channel flutter_sodium)
package:flutter/src/services/platform_channel.dart 154:7 MethodChannel._invokeMethod
00:12 +1 -1: Some tests failed.
I have no Issues implementing the package, But when I test it. I get this issue.
Hi guys,
when building the example app for iOS Simulator I'm getting this error:
ld: in /Users/peter/Downloads/flutter_sodium-master/example/ios/Pods/../.symlinks/plugins/flutter_sodium/ios/libsodium.a(libsodium_la-aead_chacha20poly1305.o), building for iOS Simulator, but linking in object file built for iOS, file '/Users/peter/Downloads/flutter_sodium-master/example/ios/Pods/../.symlinks/plugins/flutter_sodium/ios/libsodium.a' for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Which suggests that libsodium.a
does not support arm64 architecture.
Anyone can help with this?
Thanks,
Peter
The plugin flutter_sodium
is built using an older version of the Android plugin API which assumes that it's running in a full-Flutter environment. It may have undefined behaviors when Flutter is integrated into an existing app as a module.
The plugin can be updated to the v2 Android Plugin APIs by following https://flutter.dev/go/android-plugin-migration.
Process finished with exit code 0
The FFI implementation has recently been started in the ffi branch. Tracking progress of the entire libsodium API (725 symbols):
Is it possible to encrypt and decrypt files using this package?
Since I've updated flutter_sodium from 0.0.11 to 0.1.13, the hashString method crashes on Android 10 devices (reproductible in the emulator).
Here is an example stack trace (please ignore the non-standard format, it's from an obfuscated app):
Aa: Exception: Failed to store chat messages crypto_generichash failed with -1
File "unparsed", in Warning: This VM has been configured to produce stack traces that violate the Dart standard.
File "unparsed", in *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
File "unparsed", in pid: 26645, tid: 26679, name 1.ui
File "unparsed", in isolate_instructions: c0f92000 vm_instructions: c0f8e000
File "unparsed", in #0 Result|mustSucceed (package:flutter_sodium/src/extensions.dart:31)
File "unparsed", in #1 Sodium.cryptoGenerichash (package:flutter_sodium/src/sodium.dart:620)
File "unparsed", in #2 GenericHash.hash (package:flutter_sodium/src/generic_hash.dart:14)
File "unparsed", in #3 GenericHash.hashString (package:flutter_sodium/src/generic_hash.dart:19)
It works fine on Android 9 devices (and below as far as I could test) and the hash method of version 0.0.11 of flutter_sodium works fine on Android 10 devices
EDIT : This is with flutter 1.17.5
Xcode 10 includes a new build system that fails with the following error when building a flutter app with the flutter_sodium plugin:
Multiple commands produce '/[app_folder]/build/ios/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework':
Apparently any flutter iOS app with a dependency on CocoaPods will fail with this error. A workaround is available, you either can choose to fall back to the legacy build system, or update the iOS build settings.
Until this is fixed in the flutter tooling, you'll need to apply above workaround for iOS when using flutter_sodium in your flutter app.
Hey,
I want to publish my app to flathub.
As flathub links the libraries to /app/libs, I am not able to run my app properly, because the 0.2.0 release on pub.dev is statically linked to /usr/local/libs.
If you publish a newer version, I could publish my app (or at least come a step closer to it).
That would be pretty nice from you.
Thank you very much!
flutter_sodium works fine, thanks for the great work. I do get a deprecation warning when building on Android though:
Configuration 'compile' in project ':flutter_sodium' is deprecated. Use 'implementation' instead.
Versions:
flutter_sodium: "^0.0.4"
Gradle 4.8
Flutter 0.5.1
See title
Is it possible to add a version of Sodium.cryptoBox* to use XChaCha20 instead of XSalsa20?
libsodium already support this although undocumented:
jedisct1/libsodium@ccb842f
Is it executing the libsodium-jni calls in android on the main thread?
I/Choreographer( 5283): Skipped 67 frames! The application may be doing too much work on its main thread.
This happens when doing crypto calls like Argon2.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.