Last active
August 29, 2015 14:16
-
-
Save Roemerb/20115dd70990a52af35a to your computer and use it in GitHub Desktop.
C Mcrypt Rijndael-256 en/decryptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Encrypts and decrypts text in Rijndael-256. | |
When compiling, make sure you have libmcrypt installed and use the -lmcrypt flag for GCC. | |
To install libmcrypt on Ubuntu/Debian/Elementary: (sudo) apt-get install libmcrypt-dev | |
Copyright Roemer Bakker - 2015 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <mcrypt.h> | |
#include <math.h> | |
#include <stdint.h> | |
int encrypt( | |
void* buffer, | |
int buffer_len, | |
char* IV, | |
char* key, | |
int key_len | |
) { | |
MCRYPT td = mcrypt_module_open("rijndael-256", NULL, "cbc", NULL); | |
int blocksize = mcrypt_enc_get_block_size(td); | |
if (buffer_len % blocksize != 0) {return 1;} | |
mcrypt_generic_init(td, key, key_len, IV); | |
mcrypt_generic(td, buffer, buffer_len); | |
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-256", NULL, "cbc", NULL); | |
int blocksize = mcrypt_enc_get_block_size(td); | |
if (buffer_len % blocksize != 0) {return 1;} | |
mcrypt_generic_init(td,key,key_len,IV); | |
mdecrypt_generic(td,buffer,buffer_len); | |
mcrypt_generic_deinit(td); | |
mcrypt_module_close(td); | |
return 0; | |
} | |
void display(char* ciphertext,int len) { | |
int v; | |
for(v=0;v<len;v++) { | |
printf("%d",ciphertext[v]); | |
} | |
printf("\n"); | |
} | |
int main() { | |
MCRYPT td, td2; | |
char * plaintext= "w0w such secret."; | |
char* IV = "AAAAAAAAAAAAAAAA"; | |
char *key = "0123456789abcdef0123456789abcdef"; | |
int keysize = 16; | |
char* buffer; | |
int buffer_len = 16; | |
buffer = calloc(1, buffer_len); | |
strncpy(buffer, plaintext, buffer_len); | |
printf("plain: %s\n", plaintext); | |
encrypt(buffer, buffer_len, IV, key, keysize); | |
printf("Encrypted: "); display(buffer, buffer_len); | |
decrypt(buffer, buffer_len, IV, key, keysize); | |
printf("Decrypted: %s\n",buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment