Fast and powerful cryptographic functions for Flutter.
About
The goal of this plugin is to provide a fast and powerful cryptographic functions by calling native libraries. On Android, it uses javax.cypto, and on iOS, it uses CommonCrypto and CryptoKit
I started this projet because I wanted to add cryptographic functions on a Flutter app. But I faced a problem with the well-known Pointy Castle library: the performance was very poor. Here some benchmarks and comparison:
For comparison, on a iPhone 13, you can encrypt/decrypt a message of 2MiB in ~5.6s with PointyCastle and in ~40ms with NativeCrypto. And on an OnePlus 5, you can encrypt/decrypt a message of 50MiB in ~6min30 with PointyCastle and in less than ~1s with NativeCrypto.
In short, NativeCrypto is incomparable with PointyCastle.
Usage
First, check compatibility with your targets.
iOS | Android | MacOS | Linux | Windows | Web |
---|---|---|---|---|---|
✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
Hash
To digest a message, you can use the following function:
Uint8List hash = await HashAlgorithm.sha256.digest(message);
Note that you can find a toBytes()
method in the example app, to convert a String
to a Uint8List
.
In NativeCrypto, you can use the following hash functions: SHA-256, SHA-384, SHA-512
Keys
You can build a SecretKey
from a utf8, base64, base16 (hex) strings or raw bytes. You can also generate a SecretKey from secure random.
SecretKey secretKey = SecretKey(Uint8List.fromList([0x73, 0x65, 0x63, 0x72, 0x65, 0x74]));
SecretKey secretKey = SecretKey.fromUtf8('secret');
SecretKey secretKey = SecretKey.fromBase64('c2VjcmV0');
SecretKey secretKey = SecretKey.fromBase16('63657274');
SecretKey secretKey = await SecretKey.fromSecureRandom(256);
Key derivation
You can derive a SecretKey
using PBKDF2.
First, you need to initialize a Pbkdf2
object.
Pbkdf2 pbkdf2 = Pbkdf2(32, 1000, algorithm: HashAlgorithm.sha512);
Then, you can derive a SecretKey
from a password and salt.
SecretKey secretKey = await pbkdf2.derive(password: password, salt: 'salt');
In NativeCrypto, you can use the following key derivation function: PBKDF2
Cipher
And now, you can use the SecretKey
to encrypt/decrypt a message.
First, you need to initialize a Cipher
object.
AES cipher = AES(secretKey, AESMode.gcm);
Then, you can encrypt/decrypt your message.
CipherText encrypted = await cipher.encrypt(message);
Uint8List decrypted = await cipher.decrypt(encrypted);
After an encryption, you can use the CipherText
object to access underlying data.
Uint8List iv = encrypted.iv;
Uint8List data = encrypted.data;
Uint8List tag = encrypted.tag;
Note that data and tag are costly to access, so you should only use them if you need to !