rweather / arduinolibs

Arduino Cryptography Library
444 stars 212 forks source link

Encrypt String longer than blockSize() #64

Open Kasperdelasopa opened 3 years ago

Kasperdelasopa commented 3 years ago

Hello,

can someone provide an example how i can encrypt/decrypt a String that is longer than 16?

I'm constantly failing.

rweather commented 3 years ago

Can you provide an example of what you are trying to do? Which cipher are you trying to use?

Kasperdelasopa commented 3 years ago

I want to use either AES256, AESTiny256, or AESSmall256

I want to do something like this:

String in = "This Is a very long text, which much longer than 16";
setKey(_keyOfLength32);
String out = myEncrypt(in);

.....

String encryptedString = out;
setKey(_keyOfLength32);
String decryptedString = myDecrypt(encryptedString);

Im not able to use Strings that are longer than 16. Im looking for an example to write the functions "myEncrypt()" and "myDecrypt"

rweather commented 3 years ago

The AES block ciphers on their own are not useful for encrypting large blocks of data. They are a building block. What you need is to wrap the block cipher with a mode like CTR, GCM, EAX, or XTS. Then you can encrypt or decrypt as much data as you would like. Some brief examples here:

http://rweather.github.io/arduinolibs/classCTR.html http://rweather.github.io/arduinolibs/classGCM.html

Some background information on block cipher modes and when to apply them:

https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation

Kasperdelasopa commented 3 years ago

Thanks allot for your reply!!!

I did some tests with CTR. But it seems to cut of the last part of my strings. I have created these functions:

String My_Secure::encrypt(String msg){

    ctr.clear();
    ctr.setKey(_key, 32);
    ctr.setIV(_iv, 16);
    ctr.setCounterSize(16);

    uint8_t out[msg.length()+1];

    uint8_t in[msg.length()];
    msg.getBytes(in, msg.length());

    ctr.encrypt(out, in, msg.length());

    out[msg.length()-1] = '\0';

    return String(reinterpret_cast<const char*> (out));
}

String My_Secure::decrypt(String msg){

    ctr.clear();
    ctr.setKey(_key, 32);
    ctr.setIV(_iv, 16);
    ctr.setCounterSize(16);

    uint8_t out[msg.length()+1];

    uint8_t in[msg.length()];
    msg.getBytes(in, msg.length());

    ctr.decrypt(out, in, msg.length());

    out[msg.length()-1] = '\0';

    return String(reinterpret_cast<const char*> (out));
}

and i tested with these code:

String out = "String with a length of 65 .....................................!";
String eout = _secure->encrypt(out);
String dout = _secure->decrypt(eout);

Serial.printf("Orig: %d | Encrypted: %d | Decrypted: %d\n",out.length(), eout.length(),dout.length() );

Result:

Orig: 65 | Encrypted: 63 | Decrypted: 62

Did i missed something on ctr.setKey(_key, 32), ctr.setIV(_iv, 16), or ctr.setCounterSize(16)?

EgHubs commented 2 years ago

did you find a way to do that? would you please post it