我正在尝试了解如何使用 this c library (微型 AES-c)。作为 Web 开发人员,我希望获得 this JS fiddle 的等效 C 代码.
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);
给定要加密的消息和 secret ,代码生成加密数据并将结果转换为字符串。
我的 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,再加上当我尝试使用更长的消息时,我得到了奇怪的结果,这让我认为我以错误的方式使用了这个库。
问:上面的JS相当于C代码是什么?
最佳答案
我是您引用的 AES 库的原作者。
当使用 ECB 和 CBC 操作模式时,您需要确保您的 key 、iv 和输入/输出 block 都是 16 字节长。您还需要决定要使用哪种填充方案。
您可以使用 CTR 模式来避免填充并不再担心 block 大小。这通常会使 AES 算法更易于使用,因为要处理的边缘情况更少。
顺便说一句,这在项目自述文件中也有说明:
No padding is provided so for CBC and ECB all buffers should be mutiples of 16 bytes. For padding PKCS7 is recommendable.
ECB mode is considered unsafe for most uses and is not implemented in streaming mode. If you need this mode, call the function for every block of 16 bytes you need encrypted. See wikipedia's article on ECB for more details.
编辑:
如果你扩展你的数组,使它们的长度为 16 个字节并用零填充它们(或者,将它们声明为静态的,这样它们将自动进行零初始化),我认为它应该适合你:)
关于javascript - C - 使用 AES 加密和解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50254710/