Skip to content
This repository has been archived by the owner on Dec 23, 2020. It is now read-only.

Commit

Permalink
Add an AES encryption and decryption example
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenroose committed Oct 4, 2018
1 parent da19531 commit 9974354
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
48 changes: 48 additions & 0 deletions example/aes.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
library example.aes;

import "dart:convert";
import "dart:typed_data";

import "package:hex/hex.dart";
import "package:pointycastle/pointycastle.dart";

void main() {
// Key must be multiple of block size (16 bytes).
var key = new Digest("SHA-256").process(
utf8.encode("correct horse battery staple"));
// Can be anything.
var message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed d"
"o eiusmod tempor incididunt ut labore et dolore magna aliqua.";
// The initialization vector must be unique for every message, so it is a
// good idea to use a message digest as the IV.
// IV must be equal to block size (16 bytes).
var iv = new Digest("SHA-256").process(utf8.encode(message)).sublist(0, 16);
// The parameters your cipher will need. (PKCS7 does not need params.)
CipherParameters params = new PaddedBlockCipherParameters(
new ParametersWithIV(new KeyParameter(key), iv), null);

print("Message: \n$message");

////////////////
// Encrypting //
////////////////
// As for why you would need CBC mode and PKCS7 padding, consult the internet
// (f.e. http://www.di-mgt.com.au/properpassword.html).
BlockCipher encryptionCipher = new PaddedBlockCipher("AES/CBC/PKCS7");
encryptionCipher.init(true, params);
Uint8List encrypted = encryptionCipher.process(utf8.encode(message));

print("Encrypted: \n" + HEX.encode(encrypted));


////////////////
// Decrypting //
////////////////
BlockCipher decryptionCipher = new PaddedBlockCipher("AES/CBC/PKCS7");
decryptionCipher.init(false, params);
String decrypted = utf8.decode(decryptionCipher.process(encrypted));

print("Decrypted: \n$decrypted");
}
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ dev_dependencies:
build_runner: ^0.10.0
build_test: ^0.10.2
build_web_compilers: ^0.4.0
hex: ">=0.1.1 <1.0.0"
matcher: ">=0.12.0 <0.13.0"
test: ">=0.12.30 <1.4.0"
analyzer: "0.32.4"
Expand Down

0 comments on commit 9974354

Please sign in to comment.