MbedTLS AES 128在Java中加密和解密
我试图在运行FreeRTOS和mbedTLS的微处理器上加密一些文本。我正在使用AES 128 CBC和PKCS7填充。如果我尝试在文本长度小于16个字符时用mbedTLS加密并用Java解密,它就可以工作。我可以用Java解密它,文本匹配。如果它更长,那么它就不再工作。我做错了什么 mbedTLS代码:MbedTLS AES 128在Java中加密和解密,java,c,cryptography,bouncycastle,mbedtls,Java,C,Cryptography,Bouncycastle,Mbedtls,我试图在运行FreeRTOS和mbedTLS的微处理器上加密一些文本。我正在使用AES 128 CBC和PKCS7填充。如果我尝试在文本长度小于16个字符时用mbedTLS加密并用Java解密,它就可以工作。我可以用Java解密它,文本匹配。如果它更长,那么它就不再工作。我做错了什么 mbedTLS代码: unsigned char key[17] = "asdfghjklqwertzu"; unsigned char iv[17] = "qwertzuiopasd
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抛出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能否提供更新和完成功能使用的简短示例?谢谢,因为它是在评论中写的,现在仍然不起作用。下面是您的代码以及@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;
}
如果我稍微修改Java端并使用以下命令传输消息:
byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");
其中hexStringToByteArray取自此答案:
我在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;
}
公共可选测试(){
字符串encryptionKey=“asdfghjklqwerzi”;
字符串iv=“qwertzuiopasdfgh”;
字节[]消息=hexStringToByteArray(“2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0”);
addProvider(新的BouncyCastleProvider());
试一试{
IvParameterSpec IvParameterSpec=新的IvParameterSpec(iv.getBytes());
SecretKeySpec skey=新的SecretKeySpec(encryptionKey.getBytes(),“AES”);
Cipher cipherDecrypt=Cipher.getInstance(“AES/CBC/PKCS7Padding”);
cipherDecrypt.init(Cipher.DECRYPT_模式,skey,ivParameterSpec);
返回可选的.ofNullable(ByteString.copyFrom(cipherDecrypt.doFinal(message));
}捕获(BadPaddingException | IllegalBlockSizeException | InvalidGorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e){
System.out.println(“消息解密期间出错:+e”);
}
返回null;
}
它最终在调试控制台上提供以下输出:
Optional[<ByteString@1e127982 size=27 contents="hello world! test long padd">]
可选[]
这是原始消息-因此它是这样工作的。代码中仍然存在一个问题。 在设置填充模式之前,您需要设置密码信息。否则功能
mbedtls_cipher_set_padding_mode将返回错误
total_len+=olen
是错误的,尽管您没有在代码中使用它。如果我正确阅读了文档,则总长度为olen
。我怀疑在代码的另一部分中,您正在编写或发送总长度
字节以供java解密。由于未设置当前位置,因此输出
中的内容会被每次mbedtls\u密码更新
或mbedtls\u密码完成
覆盖。在这两种情况下,mbedtls\u cipher\u update
和mbedtls\u cipher\u finish
,输出必须替换为output+total\u len
。顺便说一句,一个mbedtls\u cipher\u update
和mbedtls\u cipher\u finish
调用就足够了(但这个实现可能更适合探索)。我尝试了你们两位写的东西,但仍然不起作用。你能检查一下代码编辑吗?谢谢。\u update
从输出开始,给出一个长度,称为len1<代码>\u final
应该从output+len1
开始,然后给你另一个长度,比如len2;总密文为len1+len2
。注意@Topaco说“更新和完成都必须是…”output+total\u len
“谢谢@Topaco和dave\u thompson\u 085的帮助。
byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");
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">]