0

我正在尝试使用 mbedTLS 在运行 FreeRTOS 的微处理器上加密一些文本。我正在使用带有 PKCS7 填充的 AES 128 CBC。如果我尝试在 mbedTLS 中加密并在文本短于 16 个字符时在 Java 中解密,它可以工作。我可以用 Java 解密它并且文本匹配。如果它更长,那么它不再起作用。我究竟做错了什么?

mbedTLS 代码:

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代码:

        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 抛出 javax.crypto.BadPaddingException:垫块损坏

谢谢

// 编辑:

尝试了一种更新方法,但仍然没有运气,同样的例外:

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 获得了 64 字节的数据,但仍然抛出相同的异常。

Topaco 请您提供更新和完成功能使用的简短示例吗?谢谢

4

2 回答 2

1

由于它是在评论中写的,它仍然不起作用。这里是您的代码以及@Topaco 在评论中建议的更改:

#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;
}

测试

我添加了另外两行:

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

这给出了输出:

2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0

如果我稍微修改 Java 端并使用以下命令传输消息:

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

其中 hexStringToByteArray 取自此答案:https ://stackoverflow.com/a/140861/2331445

我在Java方面得到以下代码:

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;
}

最后在调试控制台上提供以下输出:

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

那是原始消息 - 所以它是这样工作的。

于 2020-08-13T20:08:27.150 回答
0

您的代码中仍然存在一个问题。在设置填充模式之前,您需要设置密码信息。否则函数 mbedtls_cipher_set_padding_mode 将返回错误

于 2021-06-01T02:35:02.153 回答