Advertisement
Sebuahhobi98

AES Arduino

Sep 21st, 2022
1,497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. byte aes_key[] = {0xA6, 0x39, 0x6, 0xE0, 0x35, 0x8C, 0x18, 0x7D, 0xDC, 0xF5, 0xB8, 0x2D, 0xA5, 0x83, 0x76, 0x46, 0xF0, 0x28, 0xF3, 0x988};
  2.  
  3. byte aes_iv[] = {0x48, 0x6C, 0x69, 0xCA, 0x8F, 0x66, 0xAF, 0x1B, 0xAD, 0x30, 0x1B, 0xE6, 0x51, 0xEA, 0x08, 0x89, 0xE4, 0xF4, 0x71, 0xCF, 0x00, 0xC5, 0xDC, 0x3C, 0x33, 0x0B, 0xCE, 0xD7, 0x6A, 0x8C, 0x97, 0xCF};
  4.  
  5. void aes_init() {
  6.   aesLib.gen_iv(aes_iv);
  7.   aesLib.set_paddingmode((paddingMode)0);
  8. }
  9.  
  10. String encrypt(char * msg, byte iv[]) {
  11.   unsigned long ms = micros();
  12.   int msgLen = strlen(msg);
  13.   char encrypted[2 * msgLen];
  14.   aesLib.encrypt64(msg, msgLen, encrypted, aes_key, sizeof(aes_key), iv);
  15.   //  Serial.print("Encryption took: ");
  16.   //  Serial.print(micros() - ms);
  17.   //  Serial.println("us");
  18.   return String(encrypted);
  19. }
  20.  
  21. String decrypt(char * msg, byte iv[]) {
  22.   unsigned long ms = micros();
  23.   int msgLen = strlen(msg);
  24.   char decrypted[msgLen]; // half may be enough
  25.   aesLib.decrypt64(msg, msgLen, decrypted, aes_key, sizeof(aes_key), iv);
  26.   //  Serial.print("Decryption [2] took: ");
  27.   //  Serial.print(micros() - ms);
  28.   //  Serial.println("us");
  29.   return String(decrypted);
  30. }
  31.  
  32. void setup() {
  33.     aes_init();
  34.   String encrypted = encrypt((const char*)"Rian Pratama", aes_iv);
  35.   String decrypted = decrypt((char*)encrypted.c_str(), aes_iv);
  36.   Serial.print("Encrypt: ");
  37.   Serial.println(encrypted);
  38.   Serial.print("Decrypt: ");
  39.   Serial.println(decrypted);
  40.  
  41.   String plain = encrypted;
  42.  
  43.   // decryped may contain mess if not properly padded
  44.   if (decrypted.indexOf(plain) == -1) {
  45.     Serial.println("Decryption FAILED!");
  46.     Serial.print("At:");
  47.     Serial.println(plain.indexOf(decrypted));
  48.     delay(5000);
  49.   } else {
  50.     if (plain.length() == decrypted.length()) {
  51.       Serial.println("Decryption successful.");
  52.     } else {
  53.       Serial.print("Decryption length incorrect. Plain: ");
  54.       Serial.print(plain.length());
  55.       Serial.print(" dec: ");
  56.       Serial.println(decrypted.length());
  57.     }
  58.   }
  59. }
  60.  
  61. void loop(){}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement