我正在尝试使用 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 请您提供更新和完成功能使用的简短示例吗?谢谢