C - 使用 AES 加密和解密字符串 [英] C - Encrypt and decrypt a string with AES

查看:109
本文介绍了C - 使用 AES 加密和解密字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用 这个 c 库(tiny-AES-c).作为一名 Web 开发人员,我希望为 这个 JS fiddle 获得等效的 C 代码.

I'm trying to understand how to use this c library (tiny-AES-c). As a web developer, I'm looking to get an equivalent C code for this JS fiddle.

JS 代码很简单:

// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123');


console.log("Encrypted: " + ciphertext.toString());

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);

console.log("Decrypted: " + plaintext);

给定要加密的消息和秘密,代码生成加密数据并将结果转换为字符串.

Given a message to encrypt and a secret, the code generates the encrypted data and transform the results to a string.

我的 C 代码:

int main()
{
    uint8_t in[]  = "my message";
    uint8_t key[] =  "secret key 123";

    struct AES_ctx ctx;

    AES_init_ctx(&ctx, key);
    printf("ORIG: %s",(char*) in);

    // Encrypt
    AES_ECB_encrypt(&ctx, in);
    printf("\nENC: %s",(char*) in);

    // Decrypt
    AES_ECB_decrypt(&ctx, in);
    printf("\nDEC: %s",(char*) in);

    return 0;
}

输出:

ORIG: my message
ENC: ̤�+��5<n]EYK�ظ/����
DEC: my message%  

我知道我不应该尝试将结果打印为字符串,但无法弄清楚如何使用 tiny-AES-c 获得类似(与 JS)的结果API,加上当我尝试使用更长的消息时,我得到了奇怪的结果,这让我认为我以错误的方式使用了这个库.

I understand that I shouldn't try to print the result as a string, but couldn't figure out how to get similar (to the JS) results, using the tiny-AES-c API, plus when I tried using longer messages I got strange results, leading me to think I'm using this library the wrong way.

:与上述 JS 等效的 C 代码是什么?

Q: What would be the C code equivalent to the above JS?

推荐答案

正如@Morten Jensen 所建议的,您可以使用 CTR-mode IE:AES_CTR_xcrypt_buffer

As @Morten Jensen suggested, you can use the CTR-mode IE:AES_CTR_xcrypt_buffer

int main()
{
    uint8_t key[] = "secret key 123";
    uint8_t in[]  = "my message";
    uint8_t iv[16] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };

    printf("Length: %lu",strlen((char*)in));

    struct AES_ctx ctx;
    AES_init_ctx_iv(&ctx, key, iv);
    AES_CTR_xcrypt_buffer(&ctx, in, strlen((char*)in));
    printf("\nENC: %s",(char*) in); // don't use this string as an input

    AES_init_ctx_iv(&ctx, key, iv);
    AES_CTR_xcrypt_buffer(&ctx, in, strlen((char*)in));
    printf("\nDEC: %s",(char*) in);
    return 0;
}

记住,打印加密数据是错误的,如果你想匹配你的JS示例,你应该检查输出并将其转换为base64.

Remember, printing the encrypted data is wrong, you should go over the output and convert it to base64 if you want to match your JS example.

这篇关于C - 使用 AES 加密和解密字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆