Example of using the Enigma encryption library.

Dependencies:   Enigma

main.cpp

Committer:
hudakz
Date:
2019-09-24
Revision:
3:83f583d06005
Parent:
2:ac7a3cea1757

File content as of revision 3:83f583d06005:

#include "mbed.h"
#include "Enigma.h"

Serial      pc(USBTX, USBRX);
DigitalOut  led1(LED1);
uint8_t     plugboard[][2] = { { 4, 183 }, { 72, 247 }, { 108, 192 } }; // Define pairs of plugs connected with cords.
Enigma      enigma(Enigma::ROTOR_IV, Enigma::ROTOR_I, Enigma::ROTOR_III, 126, 247, 14, plugboard, 3);
Timer       timer;
time_t      timeElapsed;

/**
 * @brief
 * @note
 * @param
 * @retval
 */
int main()
{
    char        message[] = // A message to encrypt.
        "The Enigma machine is an encryption device developed and used\r\n"
        "in the early- to mid-20th century to protect commercial, diplomatic\r\n"
        "and military communication.\r\n"
        "It was employed extensively by Nazi Germany during World War II,\r\n"
        "in all branches of the German military.";
    uint8_t*    encrypted = new uint8_t[strlen(message)];
    uint8_t*    decrypted = new uint8_t[strlen(message) + 1];

    // Helper functions for maintenance only:
    //enigma.genRotorWiring("IV", 213); // Generate new wiring for rotor IV.
    //enigma.genReflectorWiring(6);     // Generate new wiring for the reflector.
    
    // Print the 'message'.
    pc.printf("%s\r\n\r\n", message);

    // Encrypt the 'message' to a byte array and print.
    timer.start();
    enigma.encrypt(encrypted, (uint8_t*)message, strlen(message));
    timeElapsed = timer.read_ms();
    pc.printf("It took %d ms to encrypt the message:\r\n\r\n", timeElapsed);
    for (size_t i = 0; i < strlen(message); i++) {
        if (i % 16 == 15) {
           printf("0x%.2X\r\n", encrypted[i]);
        }
        else {
            printf("0x%.2X ", encrypted[i]);
        }
    }
    printf("\r\n\r\n");

    // Decrypt the 'encrypted' byte array and print.
    timer.reset();
    enigma.decrypt(decrypted, encrypted, strlen(message));
    timeElapsed = timer.read_ms();
    pc.printf("It took %d ms to decrypt the message:\r\n\r\n", timeElapsed);
    decrypted[strlen(message)] = '\0';  // Terminate the c-style string (needed for 'printf').
    pc.printf("%s\r\n\r\n", decrypted);
    
    return 0;
}