Skip to content

Using symmetric algorithms

rubo edited this page Jul 11, 2012 · 1 revision

The following example demonstrates how to encrypt and decrypt sample data using the AES class.

var secret:String = "abc";
var data:ByteArray = new ByteArray(); // The data to encrypt.

data.writeUTFBytes(secret);

var aes:AES = new AES();

aes.iv = RandomNumberGenerator.getBytes(aes.blockSize / 8);
aes.key = RandomNumberGenerator.getBytes(aes.keySize / 8);

var aesEnc:ICryptoTransform = aes.createEncryptor();
var cipher:ByteArray = aesEnc.transformFinalBlock(data, 0, data.length);

trace(Convert.toBase64String(cipher)); // Outputs the encrypted data.

var aesDec:ICryptoTransform = aes.createDecryptor();

data = aesDec.transformFinalBlock(cipher, 0, cipher.length);
secret = data.readUTFBytes(data.bytesAvailable);

trace(secret); // Outputs the decrypted data.

To to encrypt or decrypt files or blocks of large data or to display progress status the transformBlock() and the transformFinalBlock() methods must be used.

var aes:AES = new AES();
var cipher:ByteArray = new ByteArray();
var inputBlockSize:int;
var inputOffset:int;
var outputOffset:int;
var data:ByteArray = RandomNumberGenerator.getBytes(2048); // The data to encrypt.

trace(Convert.toBase64String(data)); // Outputs the plain data.

aes.iv = RandomNumberGenerator.getBytes(aes.blockSize / 8);
aes.key = RandomNumberGenerator.getBytes(aes.keySize / 8);

var aesEnc:ICryptoTransform = aes.createEncryptor();

inputBlockSize = aesEnc.inputBlockSize;

for (inputOffset = 0, outputOffset = 0; data.length - outputOffset > inputBlockSize; inputOffset += inputBlockSize)
	outputOffset += aesEnc.transformBlock(data, inputOffset, inputBlockSize, cipher, outputOffset);

cipher.writeBytes(aesEnc.transformFinalBlock(data, outputOffset, data.length - outputOffset));

trace(Convert.toBase64String(cipher)); // Outputs the encrypted data.

var aesDec:ICryptoTransform = aes.createDecryptor();

data.clear();

for (inputOffset = 0, outputOffset = 0; cipher.length - outputOffset > inputBlockSize; inputOffset += inputBlockSize)
	outputOffset += aesDec.transformBlock(cipher, inputOffset, aesDec.inputBlockSize, data, outputOffset);

data.writeBytes(aesDec.transformFinalBlock(cipher, inputOffset, cipher.length - inputOffset));

trace(Convert.toBase64String(data)); // Outputs the decrypted data.
Clone this wiki locally