I have this code that I got from https://gist.github.com/bricef/2436364 to encrypt and decrypt data using mcrypt, but the thing is, I want to encrypt the plaintext into a text generated by the encrypting, so I can after encrypting pass that text to be decrypted.
But when I execute the code below, I get this output:
plain: myText
encrypt: myText
decrypt: myText
it didn't change anything from plain to encryption, am I doing something wrong? How do I get the value generated by the encryption so I can give back to the function to make it decrypt afterwards. I want a big hash sequence to make it more secure that can be decrypted with the same private key I used to encrypt it.
int encrypt(void* buffer, int buffer_len, char* IV, char* key, int key_len)
{
MCRYPT td = mcrypt_module_open("rijndael-128", NULL, "cbc", NULL);
int blocksize = mcrypt_enc_get_block_size(td);
int n_blocks = buffer_len / blocksize;
int i = 0;
if (buffer_len % blocksize != 0)
return 1;
mcrypt_generic_init(td, key, key_len, IV);
for (i = 0; i < n_blocks; i++)
mcrypt_generic(td, ((unsigned char*)buffer) + (i * blocksize), blocksize);
mcrypt_generic_deinit(td);
mcrypt_module_close(td);
return 0;
}
int decrypt(void* buffer, int buffer_len, char* IV, char* key, int key_len){
MCRYPT td = mcrypt_module_open("rijndael-128", NULL, "cbc", NULL);
int blocksize = mcrypt_enc_get_block_size(td);
int n_blocks = buffer_len / blocksize;
int i = 0;
if (buffer_len % blocksize != 0)
return 1;
mcrypt_generic_init(td, key, key_len, IV);
for (i = 0; i < n_blocks; i++)
mdecrypt_generic(td, ((unsigned char *)buffer) + (i * blocksize), blocksize);
mcrypt_generic_deinit(td);
mcrypt_module_close(td);
return 0;
}
int main()
{
MCRYPT td, td2;
char * plaintext = "myText";
char* IV = "AAAAAAAAAAAAAAAA";
char *key = "0123456789abcdef";
int keysize = 16; /* 128 bits */
char* buffer;
int buffer_len = 6;
buffer = calloc(1, buffer_len);
strncpy(buffer, plaintext, buffer_len);
printf("==C==\n");
printf("plain: %s\n", plaintext);
encrypt(buffer, buffer_len, IV, key, keysize);
printf("encrypt: %s\n", buffer);
decrypt(buffer, buffer_len, IV, key, keysize);
printf("decrypt: %s\n", buffer);
return 0;
}
In your code, with int buffer_len = 6;
you never execute mcrypt_generic
in encrypt
. Specifically, you have the following in encrypt
:
int n_blocks = buffer_len / blocksize;
...
mcrypt_generic_init (td, key, key_len, IV);
for (i = 0; i < n_blocks; i++)
mcrypt_generic (td, ((unsigned char *) buffer) + (i * blocksize),
blocksize);
Passing buffer_len = 6
results in n_blocks = 0
due to mcrypt_enc_get_block_size (td);
returning 16
. The simple fix is to make int buffer_len
a multiple of 16
. E.g: 16, 32, 64, ...
. With int buffer_len = 16;
, your code works fine:
output:
./bin/mcry
==C==
plain: myText
encrypt: '���J�Ꮽ
decrypt: myText