Menu

AES Example

saeed atalla

AES: Advanced Encryption Standard.

Supported Modes: GCM, CCM, ECB, CBC, CFB, OFB and CTR.

AES Example:

Generate Key:

We should first generate Symmetric key (CELIB::SymmetricKey):
AES can accepts key with size: 128, 192 or 512 bit (16, 24 or 32 byte).

For more security, CryptoEngine uses X917RNG standard - from ANSI 9.17 - (if available) to generate keys.

//Generate 128 bit key size:
CELIB::SymmetricKey key(128);
//Print key's data in (human-readable) form :
std::cout << "\nkey.toString(): " << key.toString().toStdString() << std::endl;

output:

key.toString(): (Class:[CELIB::SymmetricKey], Key-Hex:
[E8FDC001DA97CA64338D9554CB6DCE4A8885855750130CD09628AA6D406A4ACF53AAFFE01273D2B66EAED
EBB70708FD71B0E54BABDC5308E29EF6A337F635ED0384E318CD121A99FA5591C61156144485E6B790C126
92F07EEC1FA572C06745A2A80975E9CA813E539FAD594B030531838F2B36FC26ED0120A17FD8C262C948F],
 key Size: [128].)

Create AES Object and use it

After generating key, we can pass it's reference to AES Constructor:

CELIB::AES aes(key);
//! connect aes object with caller class to catch errors, more details on Error Handling page:
//connect(&aes, SIGNAL(error(QString)), this, SLOT(errorString(QString)));

//Plain & Cipher texts:
    QByteArray plain("Testing AES"), cipher, recover;
    bool isOk;

//Encrypt using ECB mode:
    aes.setOPMode(CELIB::ECB);
    //With ECB no need to iv.
    cipher = aes.encrypt(plain, &isOk);

    if(isOk)
        std::cout << "\nEncryption successful." << std::endl;
    else
        std::cout << "\nEncryption FAILED." << std::endl;

    std::cout << "\nCipher: [" << cipher.toHex().toUpper().data() << "].\n";

//Decrypt using same key and mode -and iv-:
    recover = aes.decrypt(cipher, &isOk);

    if(isOk)
        std::cout << "\nDecryption successful." << std::endl;
    else
        std::cout << "\nDecryption FAILED." << std::endl;

    std::cout << "\nRecover: [" << recover.data() << "].\n";

    Q_ASSERT(plain == recover);

Change AES object Key:

We can change key, iv or mode at any time we need-to:

//Create new key with size 256 bits:
CELIB::SymmetricKey key256(256);
QByteArray iv = QByteArray::fromHex("000102030405060708090A0B0C0D0E0F");

//Change aes object key:
aes.setKey(key256);

//Change mode:
aes.setOPMode(CELIB::CBC);

//Change iv:
aes.setIV(iv);

//Now you can use it to encrypt/decrypt as above.

//We can also print aes data in (human-readable) form:
std::cout << "\naes.toString(): " << aes.toString().toStdString() << std::endl;

/*
output:

aes.toString(): [CELIB::AES::toString():],
 Key:[!HIDDEN!], KeyLength:[32],
 IV-Hex:[000102030405060708090A0B0C0D0E0F], IVLength:[16],
 OPMode:[CBC].
*/

Note that you can encrypt/decrypt files with same way.

[Error Handling]


Related

Wiki: Home
Wiki: Error Handling

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.