gpt4 book ai didi

c - 使用 AES 加密文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:46 27 4
gpt4 key购买 nike

我正在尝试构建一个程序,接收一个文件(任意大小的 EXE),对其进行加密并将其复制到一个结构中。稍后再解密并确保它是相同的以供使用。

我很难加密然后解密文件。它似乎没有正确加密,我不知道如何测试它。

这是我的问题:

  1. 我做错了什么?
  2. 是否有更好的库可以使用 AES 进行加密?还是我应该坚持使用 openSSL
  3. 假设我想使用另一个键,比如“HelloWorld”。我可以只使用该字符串并将其用作加密算法的参数吗?我是否必须设置正确的 key 位长度?如果是,如何?

代码:

struct structData{
unsigned char * FileBuffer;
unsigned long FileSize;
//More stuff in here
};

struct Data sData;


/*
I load the data here, and fill in the data etc
*/
unsigned char Key[]={ //128bit key
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
};

unsigned char *enc_data = malloc(sData->FileSize);//Temporary holder for the File

AES_KEY enc_key;
AES_set_encrypt_key(Key,128,&enc_key);//Put key defined here
AES_encrypt(sData->FileBuffer,enc_data,&enc_key);
sData->FileBuffer = enc_data;//This should move the stuff over
//Should be encrypted here
sData->FileBuffer = enc_data;//Copy the output to the file buffer
free(enc_data);//Free memory

AES_KEY dec_key;
AES_set_decrypt_key(Key, 128,&dec_key);
AES_decrypt(sData->FileBuffer,dec_data,&dec_key);
sData->FileBuffer = dec_data;

free(dec_data);

任何事情都会有所帮助,希望我正朝着正确的方向前进,我的 C 技能有点生疏。

最佳答案

What am I doing wrong here?

好吧,这有点太开放了,无法彻底回答。

首先,您正在使用低级 AES_* 接口(interface)并在 ECB 模式下运行 AES。您没有派生 key 。而且您正在对 key 进行硬编码。

看起来您还有内存管理问题。您似乎没有在任何地方使用 FileSize


Is there a better library to encrypt using AES?

如果您打算使用 OpenSSL,那么您可能应该使用 EVP_* 接口(interface)使用经过身份验证的加密模式,例如 GCM。使用 GCM 模式,您可以获得 secret 性和真实性。参见 EVP Authenticated Encryption and Decryption在 OpenSSL wiki 上。


Lets say I wanted to use another key say "HelloWorld". Can I just use that string and use it as an argument for the encryption algorithm? Do I have to set the correct bit length of the key? If so how?

您应该派生一个 key ,而不是直接从您的密码短语中使用它。参见 EVP_BytesToKey(3)PKCS5_PBKDF2_HMAC(3)在 OpenSSL 文档中(OpenSSL wiki 没有文章或示例代码)。


... shall I stick with OpenSSL

如果您正确使用该库,那么您应该对它感到满意。

否则,您可以使用您喜欢的任何其他库。请参阅 OpenSSL wiki 的 Related Links一些替代品的页面。

关于c - 使用 AES 加密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24577566/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com