Hi All,
I am working on creating a fuction which I can pass an encrypted string to and then have it decrypt and print the data to the serial line. This all seemed pretty easy following the guidelines of @zachary’s demo here:
I have setup a test application which just encrypts a string and then passes it to my test function who’s only job is to decrypt it and print it to the serial line. Here is the code:
/* Includes ------------------------------------------------------------------*/
#include "application.h"
#include "spark_protocol.h"
#include "tropicssl/rsa.h"
#include "tropicssl/aes.h"
#include "spark_utilities.h"
//Global variables
unsigned char key[16] = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01};
unsigned char iv[16] = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01};
aes_context aes;
//Fucntions
void cbcDecrypt(String messageBody);
size_t pad(unsigned char *buf, size_t messageLength);
SYSTEM_MODE(MANUAL);
void setup(){
Serial.begin(9600);
}
void loop(){
const char *sTest = "Well isn't this just fantastic that it works.";
int length = strlen(sTest) + 1;
unsigned char buf[64];
memcpy(buf, sTest, length);
size_t paddedLength = pad(buf, length);
aes_setkey_enc(&aes, key, 128);
aes_crypt_cbc(&aes, AES_ENCRYPT, paddedLength, iv, buf, buf);
cbcDecrypt((const char*)buf);
delay(10000);
}
void cbcDecrypt(String messageBody){
const char *message = messageBody.c_str();
int length = strlen(message);
//Create input and output buffers for encryption.
unsigned char buf[length];
unsigned char oBuf[strlen(message)];
//Make sure buffers are empy
memset(buf, 0, length);
memset(oBuf, 0, strlen(message));
//Copy message into input buffer
memcpy(buf, message, length);
size_t paddedLength = pad(buf, length);
//Decrypt message into output buffer
aes_setkey_dec(&aes, key, 128);
aes_crypt_cbc(&aes, AES_DECRYPT, paddedLength, iv, buf, oBuf);
//Store first 16 decrypted characters as round key for next cbc encrypted send
for(int i = 0; i < 16; i++){
EEPROM.write(i+36, oBuf[i]);
}
//Print out the decrypted message and the length of the encrypted message received
Serial.print("Decrypted return: ");
Serial.println((char *)oBuf);
Serial.print("Return length+1 = ");
Serial.println(length);
}
size_t pad(unsigned char *buf, size_t messageLength) {
size_t paddedLength = (messageLength & ~15) + 16;
char pad = paddedLength - messageLength;
memset(buf + messageLength, pad, pad);
return paddedLength;
}
Here is the output I am getting in my log:
Decrypted return: <ðó¯)ÕL XeyÓjust fantastic that it works.
Return length+1 = 50
Decrypted return: ïéñVgÊ«ª:ßjust fantastic that it works.
Return length+1 = 50
Decrypted return: 8?uº`hþ±ìÐøÕijust fantastic that it works.
Return length+1 = 50
What in the world is going on here? Casting problem?
Thank you,
Travis Elliott