konstantinullrich / crypton Goto Github PK
View Code? Open in Web Editor NEWA simple Dart library for asymmetric encryption and digital signatures
Home Page: https://pub.dev/packages/crypton
License: MIT License
A simple Dart library for asymmetric encryption and digital signatures
Home Page: https://pub.dev/packages/crypton
License: MIT License
Invalid argument(s): Unsupported block type for private key: 82
#0 PKCS1Encoding._decodeBlock (package:pointycastle/asymmetric/pkcs1.dart:142:7)
#1 PKCS1Encoding.processBlock (package:pointycastle/asymmetric/pkcs1.dart:94:14)
#2 RSAPrivateKey._processInBlocks (package:crypton/src/rsa/private_key.dart:101:30)
#3 RSAPrivateKey.decryptData (package:crypton/src/rsa/private_key.dart:84:12)
#4 RSAPrivateKey.decrypt (package:crypton/src/rsa/private_key.dart:77:19)
#5 main (package:premium/crypton.dart:27:30)
#6 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#7 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
Sadly Pointy Castle does not provide Implement ECDH in its current version(1.0.2)
As reported by a User on Twitter
I'm able to build for other platforms just fine, but when attempting to build for the web it throws the following errors.
Launching lib/main.dart on Chrome in debug mode...
lib/main.dart:1
../../flutter/.pub-cache/hosted/pub.dartlang.org/pointycastle-3.1.3/lib/key_derivators/argon2.dart:42:27: Error: The integer literal 0xFFFFFFFFFFFFFFFF can't be represented exactly in JavaScript.
Try changing the literal to something that can be represented in Javascript. In Javascript 0x10000000000000000 is the nearest value that can be represented exactly.
static const int M32L = 0xFFFFFFFFFFFFFFFF;
^^^^^^^^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/pointycastle-3.1.3/lib/src/utils.dart:313:9: Error: The integer literal 0xFFFFFFFFFFFFFFFF can't be represented exactly in JavaScript.
Try changing the literal to something that can be represented in Javascript. In Javascript 0x10000000000000000 is the nearest value that can be represented exactly.
((0xFFFFFFFFFFFFFFFF) ^ ((1 << (64 - count)) - 1));
^^^^^^^^^^^^^^^^^^
../../flutter/.pub-cache/hosted/pub.dartlang.org/pointycastle-3.1.3/lib/src/platform_check/platform_check.dart:6:35: Error: Method not found: 'getPlatform'.
static Platform get instance => getPlatform();
^^^^^^^^^^^
Failed to compile application.
Exited (sigterm)
First of all, thank you for this useful package. @konstantinullrich It provides a lot of value.
Now my question is, when are you going with the Dart null safety train?
asn1lib & pointycastle have null safety releases, so that should not be a problem?
What causes a problem, is that if you are using crypton, the project gets stuck on old versions of asn1lib & pointycastle, which are also used by other packages, which therefore also can't be updated :(
How can I Encrypt with RSA in flutter and Decrypt in NodeJs ?
Which NodeJs package is compatible with your Crypton package ?
createSignature and verifySignature are currently deprecated but they appear in the example shown on github, I thought it would be great if we replaced these with examples using createSHA256Signature since it doesn't use strings and can be tricky to switch to.
Currently the library only generates a random RSA key and use it for encryption. Some use cases (my current use case) relies on an existing rsa public key, and the idea is to use the existing public key to encrypt a message.
Can this use case be supported? Thanks!
On Readme, there is the following:
This library is a simplified interface to interact with the pointy castle
However, the current link is an old GitHub project that is no longer working. Please point to the actual pub.dev package as it has the repository link on the right side.
New link: https://pub.dev/packages/pointycastle
You should have a way to use external keypairs so people are not limited to auto-generation.
The latest version of asn1lib requires dart ^3.0.0 and makes a number of changes re nullability in its API (commit)
As a result, while running a program that uses the crypton
package after running dart pub upgrade
, everything still runs just fine but the Dart VM now prints out the following warnings when it starts up:
../../../../.pub-cache/hosted/pub.dev/crypton-2.1.0/lib/src/rsa/private_key.dart:23:40: Warning: Operand of null-aware operation '!' has type 'Uint8List' which excludes null.
- 'Uint8List' is from 'dart:typed_data'.
asn1Parser = ASN1Parser(privateKey.contentBytes()!);
^
../../../../.pub-cache/hosted/pub.dev/crypton-2.1.0/lib/src/rsa/private_key.dart:32:17: Warning: Operand of null-aware operation '!' has type 'BigInt' which excludes null.
- 'BigInt' is from 'dart:core'.
modulus.valueAsBigInteger!,
^
../../../../.pub-cache/hosted/pub.dev/crypton-2.1.0/lib/src/rsa/private_key.dart:33:25: Warning: Operand of null-aware operation '!' has type 'BigInt' which excludes null.
- 'BigInt' is from 'dart:core'.
privateExponent.valueAsBigInteger!,
^
../../../../.pub-cache/hosted/pub.dev/crypton-2.1.0/lib/src/rsa/public_key.dart:23:56: Warning: Operand of null-aware operation '!' has type 'Uint8List' which excludes null.
- 'Uint8List' is from 'dart:typed_data'.
final publicKeyAsn = ASN1Parser(publicKeyBitString.contentBytes()!);
^
../../../../.pub-cache/hosted/pub.dev/crypton-2.1.0/lib/src/rsa/public_key.dart:29:17: Warning: Operand of null-aware operation '!' has type 'BigInt' which excludes null.
- 'BigInt' is from 'dart:core'.
modulus.valueAsBigInteger!, exponent.valueAsBigInteger!);
^
../../../../.pub-cache/hosted/pub.dev/crypton-2.1.0/lib/src/rsa/public_key.dart:29:46: Warning: Operand of null-aware operation '!' has type 'BigInt' which excludes null.
- 'BigInt' is from 'dart:core'.
modulus.valueAsBigInteger!, exponent.valueAsBigInteger!);
^
I'm happy to make a fix and send a pull request if you wish
I am investigating on how I could do this using crypton
but it seems there is no support for that, yet.
Although I managed to use directly pointycastle
but somehow I stuck on creating the salt
...
Basically, I have a public key, a message and a signature and I would verify that the signature matches the message using the public key.
var rsaPublicKey = crypton.RSAPublicKey.fromPEM(publicKey);
final signer = Signer('SHA-384/PSS');
AsymmetricKeyParameter<RSAAsymmetricKey> keyParams =
PublicKeyParameter<RSAPublicKey>(rsaPublicKey.asPointyCastle);
signer.init(
false,
ParametersWithSalt(keyParams, Uint8List()),
);
final sig = PSSSignature(base64Decode(signature));
final verified = signer.verifySignature(
Uint8List.fromList(message.codeUnits),
sig,
);
I'm not sure how to build `ParametersWithSalt(keyParams, Uint8List()' needed to initialise the signer.
Any hint is highly appreciated.
Future rsa() async {
RSAKeypair rsaKeypair = RSAKeypair.fromRandom(keySize: 1024);
print(rsaKeypair.privateKey);
print(rsaKeypair.publicKey);
var message= 'dhfdhvyurdytdycjvbnj876tyxfhcjbjhiy765etsrdgxvvhjhiyi7t6rtydfhcgvhjhiuyituydgxfcvbjhuytuyfhcvnmbjhiutiytddhfdhvyurdytdycjvbnj876tyxfhcjbjhiy765etsrdgxvvhjhiyi7t6rtydfhcgvhjhiuyituydgxfcvbjhuytuyfhcvnmbjhiutiytd';
var encrypted = rsaKeypair.publicKey.encrypt(message);
var decrypted = rsaKeypair.privateKey.decrypt(encrypted);
print(encrypted);
print(decrypted);
}
E/flutter ( 4125): [ERROR:flutter/lib/ui/ui_dart_state.cc(171)] Unhandled Exception: Invalid argument(s): Input data too large
E/flutter ( 4125): #0 PKCS1Encoding._encodeBlock
package:pointycastle/asymmetric/pkcs1.dart:101
E/flutter ( 4125): #1 PKCS1Encoding.processBlock
package:pointycastle/asymmetric/pkcs1.dart:92
E/flutter ( 4125): #2 BaseAsymmetricBlockCipher.process
package:pointycastle/…/impl/base_asymmetric_block_cipher.dart:15
E/flutter ( 4125): #3 RSAPublicKey.encryptData
package:crypton/…/rsa/public_key.dart:79
E/flutter ( 4125): #4 RSAPublicKey.encrypt
package:crypton/…/rsa/public_key.dart:72
E/flutter ( 4125): #5 AuthModel.rsa
package:class2/Test/FirebaseAuth.dart:44
E/flutter ( 4125): #6 SignIn.build.<anonymous closure>
package:class2/Test/FirebaseAuth.dart:18
E/flutter ( 4125): #7 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:993
E/flutter ( 4125): #8 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1111
E/flutter ( 4125): #9 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:183
E/flutter ( 4125): #10 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:598
E/flutter ( 4125): #11 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:287
E/flutter ( 4125): #12 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:222
E/flutter ( 4125): #13 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:476
E/flutter ( 4125): #14 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:77
E/flutter ( 4125): #15 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:122
E/flutter ( 4125): #16 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4125): #17 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:120
E/flutter ( 4125): #18 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:106
E/flutter ( 4125): #19 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:219
E/flutter ( 4125): #20 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:199
E/flutter ( 4125): #21 GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:157
E/flutter ( 4125): #22 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:103
E/flutter ( 4125): #23 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:87
E/flutter ( 4125): #24 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4125): #25 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4125): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4125): #27 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 4125): #28 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 4125):
I have a public key in XML format, does this package able to use the XML format to encrypt data? or need to convert to PEM format?
Thanks
Stacktrace:
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: RangeError (index): Index out of range: index should be less than 2: 2
E/flutter ( 6935): 0 _Uint8ArrayView.[] (dart:typed_data-patch/typed_data_patch.dart:3946:7)
E/flutter ( 6935): 1 new ASN1Boolean.fromBytes
package:asn1lib/asn1boolean.dart:20
E/flutter ( 6935): 2 ASN1Parser._doPrimitive
package:asn1lib/asn1parser.dart:91
E/flutter ( 6935): 3 ASN1Parser.nextObject
package:asn1lib/asn1parser.dart:51
E/flutter ( 6935): 4 new RSAPublicKey.fromString
package:crypton/…/rsa/public_key.dart:25
E/flutter ( 6935): 5 RSAPublicKey.fromPEM
package:crypton/…/rsa/public_key.dart:41
E/flutter ( 6935): 6 AppEncryption.initialize
package:careconnect_patient/services/app_encryption.dart:41
E/flutter ( 6935): <asynchronous suspension>
E/flutter ( 6935): 7 SplashScreen.build.<anonymous closure>
package:careconnect_patient/screens/splash_screen.dart:18
E/flutter ( 6935): 8 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 6935): 9 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 6935): 10 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter ( 6935): 11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter ( 6935): 12 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter ( 6935): 13 Future._completeWithValue (dart:async/future_impl.dart:529:5)
E/flutter ( 6935): 14 Future._asyncCompleteWithValue.<anonymous closure> (dart:async/future_impl.dart:567:7)
E/flutter ( 6935): 15 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 6935): 16 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 6935): 17 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 6935): 18 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 6935): 19 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 6935): 20 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
Code:
_serverPublicKey = RSAPublicKey.fromPEM(
"-----BEGIN RSA PUBLIC KEY-----\nMIGJAoGBALePbOELWu7hMBtuF2SKmDRZg57e0opAeA8jXo2S+qcd1gfYh/Dztkw4zkedimDvukkMAKQUpoW2gJcm+7r5dQ/ZRofGL64Gx1eeUkNjzSRESXN/bJk3bI9bZ7269tT3IcyGu6jTlqrS3EWqLF7DgnLqBnPHo+gQEpLveI3FBhL7AgMBAAE=\n-----END RSA PUBLIC KEY-----");
it only took seconds but still not fast enough because the function is synchronous and it freezes the UI. how about making it async?
Previously the key size was fixed to 2048, but in the latest version you can change. The problem is that the default has been changed. People who use this library will wonder why their code may not be working anymore (I had this problem, but I also knew this change was made so I could fix it quickly).
The default should be changed back to 2048.
For Signing and Verifying what hash Algorithm you are using?
How to verify signature using nodejs ?
Make the key size adjustable.
It should be possible to create a keypair using
RSAKeypair.fromRandom()
with adjustable key size.
maybe using an optional named param that defaults to 2048?
RSAKeypair.fromRandom({int keySize=2048})
import 'dart:typed_data';
import 'package:crypton/crypton.dart';
main() {
ECKeypair ecKeypair = ECKeypair.fromRandom();
for (int i = 0; i < 100; i++) {
String message = i.toRadixString(16);
final List<int> codeUnits = message.codeUnits;
final Uint8List unit8List = Uint8List.fromList(codeUnits);
final signature = ecKeypair.privateKey.createSHA256Signature(unit8List);
bool verified = ecKeypair.publicKey.verifySHA256Signature(unit8List, signature);
if (!verified) {
print('verified failed: $unit8List');
}
}
}
On average, the fail rate is about 5%. RSAKey seems fine though.
Use Flutter RSA with NodeJs
I want to encrypt message in Flutter and Decrypt in Nodejs, I already tryed 5-7 Nodejs Packages but I got error.
Please help me.
Hi! What is the recommended flow to encrypt images with this library? Thanks!
Code:
void main() {
var rsaKeypair = RSAKeypair.fromRandom();
var message = 'test message';
var signature = rsaKeypair.privateKey.createSHA256Signature(utf8.encode(message));
var signatureStr = utf8.decode(signature);
var verified = rsaKeypair.publicKey.verifySHA256Signature(utf8.encode(message), utf8.encode(signatureStr));
/*rsaKeypair.publicKey.verifySHA256Signature(utf8.encode(message), signature);This works fine. But I need the signature in string format to be used in my application. */
print(verified);
}
Output:
Unhandled exception:
FormatException: Bad UTF-8 encoding 0x8f (at offset 2)
#0 _Utf8Decoder.convert (dart:convert/utf.dart:532:13)
#1 Utf8Decoder.convert (dart:convert/utf.dart:329:13)
#2 Utf8Codec.decode (dart:convert/utf.dart:61:56)
I upgraded from version 1.0.6 to 1.1.0. I changed createSignature (deprecated) to createSHA256Signature.
Hello Konstantin,
I would like to use your library and am currently stuck on loading an existing certificate (with private and public key). I would like to make a signature with the private key based on SHA256withECDSA. Unfortunately, I have not found a way to load an existing file with password.
Code example of what I am thinking of:
// Load the PKCS12 file
File pkcs12File = File('path/to/your/pkcs12/file.p12');
Uint8List pkcs12Data = await pkcs12File.readAsBytes();
// Decrypt the PKCS12 file using the password
String pkcs12Password = 'your_password_here';
ECKeypair p12EccKeyPair = ECKeypair.fromPKCS12(pkcs12Data, pkcs12Password);
// Get the private key for signature
ECPrivateKey privateKey = p12EccKeyPair.privateKey;
...
I only saw that you support "fromPEM for RSA Keys.
Is there a other way to load a pkcs12?
Best regards,
Reinhard
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.