encryptString method
Encrypts a string.
The string is converted to bytes using utf8 codec.
See Cipher.encrypt for more information.
Example
In this example, we use Chacha20.poly1305Aead:
import 'package:cryptography/cryptography.dart';
Future<void> main() async {
final cipher = Chacha20.poly1305Aead();
final secretKey = await cipher.newSecretKey();
final wand = await cipher.newCipherWandFromSecretKey(secretKey);
// Encrypt
final secretBox = await wand.encryptString('Hello, world!');
print('Nonce: ${secretBox.nonce}');
print('Cipher text: ${secretBox.cipherText}');
print('MAC: ${secretBox.mac.bytes}');
// Decrypt
final clearText = await wand.decryptString(secretBox);
print('Clear text: $clearText');
}
Implementation
Future<SecretBox> encryptString(String clearText) async {
final bytes = utf8.encode(clearText) as Uint8List;
final secretBox = await encrypt(
bytes,
possibleBuffer: bytes,
);
// Cut the amount of possibly sensitive data in the heap.
// This should be a cheap operation relative to encryption.
final cipherText = secretBox.cipherText;
if (cipherText is! Uint8List ||
!identical(bytes.buffer, cipherText.buffer)) {
bytes.fillRange(0, bytes.length, 0);
}
return secretBox;
}