Advertisement
TolentinoCotesta

Crypto CBC library test

Dec 29th, 2017
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. // reference https://rweather.github.io/arduinolibs/crypto.html
  2. #include <CBC.h>
  3. #include <AES.h>
  4.  
  5. #define BLOCK_SIZE 16
  6. CBC<AES128> cbc;
  7. byte key[BLOCK_SIZE] = "_###myKey1234###";
  8. byte iv[BLOCK_SIZE];
  9. byte chiper[BLOCK_SIZE];
  10.  
  11. void setup() {
  12.   Serial.begin(115200);
  13.   // Set key
  14.   cbc.setKey(key, BLOCK_SIZE);
  15.  
  16.   // perform test
  17.   for(byte i = 0; i<5; i++){    
  18.     Serial.println();
  19.     Serial.print("Run no. ");
  20.     Serial.println(i);
  21.     test_AES128();
  22.   }
  23.  
  24. }
  25.  
  26. void loop() {
  27.   // put your main code here, to run repeatedly:
  28.  
  29. }
  30.  
  31. // Helper routine to dump a byte array as hex values to Serial.
  32. void printHex(byte *buffer, byte bufferSize) {
  33.   for (byte i = 0; i < bufferSize; i++) {
  34.     Serial.print(buffer[i] < 0x10 ? " 0" : " ");
  35.     Serial.print(buffer[i], HEX);
  36.   }
  37.   Serial.println();
  38. }
  39. void printString(byte *buffer, byte bufferSize) {
  40.   for (byte i = 0; i < bufferSize; i++) {
  41.     Serial.print((char)buffer[i]);
  42.   }
  43.   Serial.println();
  44. }
  45.  
  46. void test_AES128(){
  47.   long t1, t2 = 0;
  48.  
  49.   // Print original plain text (just for checking)
  50.   byte plain[] = "0123456789ABCDEF";
  51.   Serial.print("original plain text:");
  52.   printString(plain, sizeof(plain));
  53.   Serial.print("original plain byte:");
  54.   printHex(plain, sizeof(plain));
  55.  
  56.  
  57.   // Generate a random initialization vector  
  58.   for (int i = 0 ; i < BLOCK_SIZE ; i++ ) {
  59.     iv[i]= random(0xFF);
  60.   }
  61.  
  62.   // Set initialization vector
  63.   t1 = micros();  
  64.   cbc.setIV(iv, BLOCK_SIZE);
  65.   t2 = micros() - t1;
  66.   Serial.print(t2);
  67.   Serial.print(" uS - IV:");
  68.   printHex(iv, sizeof(iv));
  69.  
  70.   // encrypt
  71.   t1 = micros();
  72.   cbc.encrypt(chiper, plain, BLOCK_SIZE);
  73.   t2 = micros() - t1;
  74.   Serial.print(t2);
  75.   Serial.print(" uS - encrypted chiper:");
  76.   printHex(chiper, sizeof(chiper));
  77.  
  78.   // decrypt
  79.   t1 = micros();
  80.   cbc.decrypt(chiper, plain, BLOCK_SIZE);
  81.   t2 = micros() - t1;
  82.   Serial.print(t2);
  83.   Serial.print(" uS - decrypted plain:");
  84.   printHex(plain, sizeof(plain));
  85.  
  86.   cbc.clear();
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement