首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java实现MbedTLS AES128加密与解密

用Java实现MbedTLS AES128加密与解密
EN

Stack Overflow用户
提问于 2020-08-13 23:00:48
回答 2查看 558关注 0票数 0

我正在尝试用mbedTLS在运行FreeRTOS的微处理器上加密一些文本。我使用的是AES128CBC与PKCS7填充。如果我尝试在mbedTLS中加密,在Java语言中解密,当文本长度小于16个字符时,它可以工作。我可以用Java把它解密然后文本就匹配了。如果它更长,那么它就不再起作用了。我做错了什么?

mbedTLS代码:

代码语言:javascript
复制
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代码:

代码语言:javascript
复制
        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: pad块损坏

谢谢

//编辑:

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

代码语言:javascript
复制
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字节的数据,但仍然抛出了相同的异常。

请您提供更新和完成函数用法的简短示例?谢谢

EN

回答 2

Stack Overflow用户

发布于 2020-08-14 04:08:27

因为它是在评论中写的,所以它仍然不能工作。下面是您的代码以及@Topaco在注释中建议的更改:

代码语言:javascript
复制
#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;
}

测试

我添加了两行:

代码语言:javascript
复制
for (int i = 0; i < total_len; i++)
    printf("%02X", output[i]);

这将给出输出:

代码语言:javascript
复制
2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0

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

代码语言:javascript
复制
byte[] message = hexStringToByteArray("2FE64A72125E30B15C376FD2142D36FA778142DC4FD4A1F36EECDBCDA19BFAA0");

hexStringToByteArray取自这个答案:https://stackoverflow.com/a/140861/2331445

我在Java端得到了以下代码:

代码语言:javascript
复制
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;
}

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

代码语言:javascript
复制
Optional[<ByteString@1e127982 size=27 contents="hello world! test long padd">]

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

票数 1
EN

Stack Overflow用户

发布于 2021-06-01 10:35:02

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63397882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档