0

I am trying to encrypt some text on microprocessor running FreeRTOS with mbedTLS. I am using AES 128 CBC with PKCS7 padding. If I try to encrypt in mbedTLS and decrypt in Java when text is shorter than 16 characters it works. I can decrypt it in Java and the text matches. If it is longer then it no longer works. What am I doing wrong?

mbedTLS code:

unsigned char key[17] = "asdfghjklqwertzu";
unsigned char iv[17] = "qwertzuiopasdfgh";
unsigned char output[1024];
size_t olen;
size_t total_len = 0;

mbedtls_cipher_context_t ctx;
mbedtls_cipher_init(&ctx);
mbedtls_cipher_set_padding_mode(&ctx, MBEDTLS_PADDING_PKCS7);
mbedtls_cipher_setup(&ctx,
        mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, 128,
                MBEDTLS_MODE_CBC));
mbedtls_cipher_setkey(&ctx, key, 128, MBEDTLS_ENCRYPT);
mbedtls_cipher_set_iv(&ctx, iv, 16);
mbedtls_cipher_reset(&ctx);

char aa[] = "hello world! test long padd";
for( int offset = 0; offset < strlen(aa); offset += mbedtls_cipher_get_block_size( &ctx ) ) {
    int ilen = ( (unsigned int) strlen(aa) - offset > mbedtls_cipher_get_block_size( &ctx ) ) ?
            mbedtls_cipher_get_block_size( &ctx ) : (unsigned int) ( strlen(aa) - offset );

      char sub[100];

      strncpy ( sub, aa+offset, ilen );
      unsigned char* sub2 = reinterpret_cast<unsigned char *>(sub);
      mbedtls_cipher_update(&ctx, sub2, ilen, output, &olen);
      total_len += olen;
}
// After the loop
mbedtls_cipher_finish(&ctx, output, &olen);
total_len += olen;
mbedtls_cipher_free(&ctx);

Java code:

        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
            SecretKeySpec skey = new SecretKeySpec(encryptionKey.getBytes(), "AES");
            Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipherDecrypt.init(Cipher.DECRYPT_MODE, skey, ivParameterSpec);
            return Optional.ofNullable(ByteString.copyFrom(cipherDecrypt.doFinal(message.toByteArray())));
        } catch (BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
            log.error("Error during message decryption: ", e);
        }

Java throws javax.crypto.BadPaddingException: pad block corrupted

Thanks

// EDIT:

Tried with one update approach and still no luck, the same exception:

unsigned char key[17] = "asdfghjklqwertzu";
unsigned char iv[17] = "qwertzuiopasdfgh";
//unsigned char buffer[1024];
unsigned char output[1024];
size_t olen;

unsigned char text[] = "abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc";

mbedtls_cipher_context_t ctx;
mbedtls_cipher_init(&ctx);
mbedtls_cipher_set_padding_mode(&ctx, MBEDTLS_PADDING_PKCS7);
mbedtls_cipher_setup(&ctx,
        mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, 128,
                MBEDTLS_MODE_CBC));
mbedtls_cipher_setkey(&ctx, key, 128, MBEDTLS_ENCRYPT);
mbedtls_cipher_set_iv(&ctx, iv, 16);
mbedtls_cipher_reset(&ctx);
mbedtls_cipher_update(&ctx, text, strlen((char*) text), output, &olen); // Olen is 48
mbedtls_cipher_finish(&ctx, output, &olen); // Olen is 16
mbedtls_cipher_free(&ctx);

// 48 + 16 = 64 which is according to https://www.devglan.com/online-tools/aes-encryption-decryption correct

Java gets a 64 bytes of data but still throws the same exception.

Topaco please can you provide short example of usage of update and finish functions? Thank you

WebScript
  • 67
  • 6
  • 1
    `total_len += olen;` is wrong, although you don't do anything with it in your code. The total length is `olen`, if I'm reading the documentation correctly. I suspect in another part of your code you are writing or sending `total_length` bytes to be decrypted by java. – President James K. Polk Aug 13 '20 at 16:53
  • The content in `output` is overwritten with every `mbedtls_cipher_update` or `mbedtls_cipher_finish`, because the _current_ position is not set. In both, `mbedtls_cipher_update` and `mbedtls_cipher_finish`, `output` must be replaced by `output + total_len`. By the way, a _single_ `mbedtls_cipher_update` and `mbedtls_cipher_finish` call is sufficient (but this implementation is probably more for exploration). – Topaco Aug 13 '20 at 17:46
  • I tried to do what both of you wrote, but it still does not work. Can you please check the code edit? Thank you. – WebScript Aug 13 '20 at 19:29
  • `_update` starts at `output` and gives you one length, call it len1. **`_final` should start at `output + len1`** and give you _another_ length say len2; the total ciphertext is `len1 + len2`. Notice @Topaco said "**both** `_update` and `-finish` ... must be ... `output + total_len`" – dave_thompson_085 Aug 13 '20 at 20:08
  • Thank you @Topaco and dave_thompson_085 for your help. – WebScript Aug 25 '20 at 16:25

2 Answers2

1

Since it was written in comments that it still doesn't work. Here your code with the changes suggested by @Topaco in the comments:

#include <stdio.h>
#include <string.h>
#include <mbedtls/cipher.h>

int main() {
    unsigned char key[17] = "asdfghjklqwertzu";
    unsigned char iv[17] = "qwertzuiopasdfgh";
    unsigned char output[1024];
    size_t olen;
    size_t total_len = 0;

    mbedtls_cipher_context_t ctx;
    mbedtls_cipher_init(&ctx);
    mbedtls_cipher_set_padding_mode(&ctx, MBEDTLS_PADDING_PKCS7);
    mbedtls_cipher_setup(&ctx,
                         mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, 128,
                                                         MBEDTLS_MODE_CBC));
    mbedtls_cipher_setkey(&ctx, key, 128, MBEDTLS_ENCRYPT);
    mbedtls_cipher_set_iv(&ctx, iv, 16);
    mbedtls_cipher_reset(&ctx);

    char aa[] = "hello world! test long padd";
    for (int offset = 0; offset < strlen(aa); offset += mbedtls_cipher_get_block_size(&ctx)) {
        int ilen = ((unsigned int) strlen(aa) - offset > mbedtls_cipher_get_block_size(&ctx)) ?
                   mbedtls_cipher_get_block_size(&ctx) : (unsigned int) (strlen(aa) - offset);

        char sub[100];

        strncpy (sub, aa + offset, ilen);
        unsigned char *sub2 = (unsigned char *) (sub);
        mbedtls_cipher_update(&ctx, sub2, ilen, output + total_len, &olen);
        total_len += olen;
    }
    mbedtls_cipher_finish(&ctx, output + total_len, &olen);
    total_len += olen;
    for (int i = 0; i < total_len; i++)
        printf("%02X", output[i]);
    mbedtls_cipher_free(&ctx);
    return 0;
}

Test

I added two additional lines:

for (int i = 0; i < total_len; i++)
    printf("%02X", output[i]);

This gives the output:

2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0

If I modify Java side a bit and transfer message with:

byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");

where hexStringToByteArray is taken from this answer: https://stackoverflow.com/a/140861/2331445

I get on Java side the following code:

public Optional<ByteString> test() {
    String encryptionKey = "asdfghjklqwertzu";
    String iv = "qwertzuiopasdfgh";
    byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");
    Security.addProvider(new BouncyCastleProvider());

    try {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        SecretKeySpec skey = new SecretKeySpec(encryptionKey.getBytes(), "AES");
        Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipherDecrypt.init(Cipher.DECRYPT_MODE, skey, ivParameterSpec);
        return Optional.ofNullable(ByteString.copyFrom(cipherDecrypt.doFinal(message)));
    } catch (BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
        System.out.println("Error during message decryption: " + e);
    }
    return null;
}

which finally gives the following output onto the debug console:

Optional[<ByteString@1e127982 size=27 contents="hello world! test long padd">]

That is the original message - so this way it works.

Stephan Schlecht
  • 26,556
  • 1
  • 33
  • 47
0

There is still one issue left in your code. You will need to setup cipher info before setting padding mode. Otherwise function mbedtls_cipher_set_padding_mode will return an error