Reputation: 3239
I am trying to build a program the takes in a file (an EXE of arbitrary size), encrypts its and copies it to a structure. Then decrypt it later and make sure it is the same for use.
I am having a hard time encrypting then decrypting the file. It seems to not be encrypting properly and I do not know how to test it.
Here are my questions:
Code:
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);
Anything would help, hopefully I am heading in the right direction, my C skills are a bit rusty.
Upvotes: 1
Views: 2760
Reputation: 248
Here is my example of AES encryption with Javascript.
The live platform is here
The AES code is located here
Upvotes: 0
Reputation: 102376
What am I doing wrong here?
Well, that's a bit too open ended to answer thoroughly.
Starting with the obvious, you are using low-level AES_*
interfaces and operating AES in ECB mode. You are not deriving your key. And you are hard coding a key.
It also looks like you have memory management problems. You don't appear to use FileSize
anywhere.
Is there a better library to encrypt using AES?
If you are going to use OpenSSL, then you should probably use the EVP_*
interfaces and use an authenticated encryption mode like GCM. With GCM mode, you get confidentiality and authenticity. See EVP Authenticated Encryption and Decryption on the 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?
You should derive a key rather than use it directly from your passphrase. See EVP_BytesToKey(3)
and PKCS5_PBKDF2_HMAC(3)
in the OpenSSL docs (the OpenSSL wiki does not have an article or example code).
... shall I stick with OpenSSL
If you use the library correctly, then you should be happy with it.
Otherwise, you can use any other library you like. See the OpenSSL wiki's Related Links page for some alternatives.
Upvotes: 4