encrypt
- Dart course
- Advanced
- Lesson 69/83
- 5 min
Learn encryption with the encrypt package.
The encrypt package
encrypt is Dart's symmetric encryption package. It uses the AES algorithm. It is imported with import 'package:encrypt/encrypt.dart';. It works with the Encrypter, Key and IV classes.
Example: final key = Key.fromUtf8('16baytlikkey1234'); final iv = IV.fromUtf8('16baytlikiv01234'); final encrypter = Encrypter(AES(key)); final encrypted = encrypter.encrypt('msg', iv: iv);. Here AES encryption is done with a 16-byte key and an initialization vector (IV). The result is an Encrypted object; .base64 turns it into a base64 string.
The AES encryption flow
AES encryption works with three parts: Key (key), IV (initialization vector) and Encrypter. The key is secret for encryption; the IV is a value that should differ per message.
To decrypt use encrypter.decrypt(encrypted, iv: iv). Data encrypted with a key and IV is decrypted with the same key and IV. This is the foundation of symmetric encryption: the same key is used for both encryption and decryption. In this lesson we define the encryption function.
Practice Define an encryption function
Add import 'package:encrypt/encrypt.dart';. Define encryptMessage(String msg, Key key, IV iv) with final encrypter = Encrypter(AES(key)); and return encrypter.encrypt(msg, iv: iv).base64; inside. In main add print('encrypt: AES encryption') and print('Output: base64 ciphertext').
Starter code
// import the encrypt package
// define encryptMessage (Encrypter + AES)
void main() {
// print encrypt info
}Sample solution
import 'package:encrypt/encrypt.dart';
String encryptMessage(String msg, Key key, IV iv) {
final encrypter = Encrypter(AES(key));
return encrypter.encrypt(msg, iv: iv).base64;
}
void main() {
print('encrypt: AES encryption');
print('Output: base64 ciphertext');
}Expected output
encrypt: AES encryption Output: base64 ciphertext
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the encrypt parts
| Term | Meaning |
|---|---|
encrypt |
Encryption package |
AES |
Algorithm |
Encrypter |
Encrypter |
IV |
Init vector |
2 Which algorithm does the encrypt package use?
- AES Correct answer
- MD5
- SHA
- RSA
Explanation: the encrypt package uses the AES algorithm.
3 Creating an Encrypter
final encrypter = ____(AES(key));
final encrypter = Encrypter(AES(key));
Explanation: Encrypter(AES(key)) creates an encrypter.