AES Manual

About

An Advanced Encryption Standard (AES, also known as Rijndael) class to encrypt/decrypt data.

// This example demonstrates the encryption and decryption of a string.
// Some plain text to encrypt.
const Char plainText[] = "O brave new world That has such people in!";
const Int32 length = sizeof(plainText);
GePrint("Plain Text: " + String(plainText));
// Declare secret key and encryption block size.
const Int32 blockSize = 256; // in bits (either 128, 192 or 256)
const Char key[32] = { '7', 'c', '3', '0', 'e', '0', '0', 'b', 'b', '6', '2', '7', '1', '4', '9', '5' }; // either 16, 24 or 32 bytes
const Int32 keyLength = sizeof(key) * 8; // in bits (either 128, 192 or 256)
DebugAssert((keyLength == 128) || (keyLength == 192) || (keyLength == 256));
// Memory to store the encrypted data.
void* buffer = nullptr;
Int encryptedSize = 0;
// Encrypt data.
{
// Get size of the memory needed to store the encrypted data.
encryptedSize = AES::CalcEncryptedDataSize(blockSize, length);
DebugAssert(encryptedSize >= length); // Note: encrytedSize is always equal or larger than unencrypted size.
// Allocate needed memory.
buffer = NewMem(char, encryptedSize); // No need to clear memory here, will be filled with random data next.
if (!buffer)
return false;
// Fill buffer with random content for increased security (the buffer part behind plainText is also input to the encryption).
if (!SecureRandom::GetRandomNumber(srp, buffer, encryptedSize))
return false;
// Copy the given text into the memory.
CopyMem(plainText, buffer, length);
if (aes && aes->Init(blockSize, keyLength))
{
aes->Encrypt(buffer, encryptedSize, key);
}
}
// Decrypt data again.
{
if (buffer && aes && aes->Init(blockSize, keyLength))
{
if (aes->Decrypt(buffer, encryptedSize, key))
{
GePrint("Decrypted Data: " + String((char*)buffer));
}
}
}
DeleteMem(buffer);

Create

AES objects are created with the usual tools, see Entity Creation and Destruction Manual.

Use

  • AES::Init(): Initializes the AES cipher to the given block length and key length.
  • AES::CalcEncryptedDataSize(): Calculates the size of the data block (data size + encryption overhead).
    Note
    The encrypted data size is always equal or larger than the unencrypted data size.

Encryption / Decryption

  • AES::Encrypt(): Encrypts a data block.
  • AES::Decrypt(): Decrypts a data block.
    Note
    Use a buffer of encrypted data size for both operations.
    Warning
    It is recommended to fill the end of the buffer (encrypted size >= data size, so the part after the data to encrypt) with random values (e.g. via SecureRandom) to increase security.

Further Reading