Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. /*
  2. Encrypts and decrypts text in Rijndael-256.
  3. When compiling, make sure you have libmcrypt installed and use the -lmcrypt flag for GCC.
  4. To install libmcrypt on Ubuntu/Debian/Elementary: (sudo) apt-get install libmcrypt-dev
  5.  
  6. Copyright Roemer Bakker - 2015
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11.  
  12. #include <mcrypt.h>
  13.  
  14. #include <math.h>
  15. #include <stdint.h>
  16.  
  17. int encrypt(
  18. void* buffer,
  19. int buffer_len,
  20. char* IV,
  21. char* key,
  22. int key_len
  23. ) {
  24. MCRYPT td = mcrypt_module_open("rijndael-256", NULL, "cbc", NULL);
  25. int blocksize = mcrypt_enc_get_block_size(td);
  26. if (buffer_len % blocksize != 0) {return 1;}
  27.  
  28. mcrypt_generic_init(td, key, key_len, IV);
  29. mcrypt_generic(td, buffer, buffer_len);
  30. mcrypt_generic_deinit(td);
  31. mcrypt_module_close(td);
  32.  
  33. return 0;
  34. }
  35.  
  36. int decrypt(
  37. void* buffer,
  38. int buffer_len,
  39. char* IV,
  40. char* key,
  41. int key_len
  42. ) {
  43. MCRYPT td = mcrypt_module_open("rijndael-256", NULL, "cbc", NULL);
  44. int blocksize = mcrypt_enc_get_block_size(td);
  45. if (buffer_len % blocksize != 0) {return 1;}
  46.  
  47. mcrypt_generic_init(td,key,key_len,IV);
  48. mdecrypt_generic(td,buffer,buffer_len);
  49. mcrypt_generic_deinit(td);
  50. mcrypt_module_close(td);
  51.  
  52. return 0;
  53. }
  54.  
  55. void display(char* ciphertext,int len) {
  56. int v;
  57. for(v=0;v<len;v++) {
  58. printf("%d",ciphertext[v]);
  59. }
  60. printf("\n");
  61. }
  62.  
  63. int main() {
  64. MCRYPT td, td2;
  65. char * plaintext= "w0w such secret.";
  66. char* IV = "AAAAAAAAAAAAAAAA";
  67. char *key = "0123456789abcdef0123456789abcdef";
  68. int keysize = 16;
  69. char* buffer;
  70. int buffer_len = 16;
  71.  
  72. buffer = calloc(1, buffer_len);
  73. strncpy(buffer, plaintext, buffer_len);
  74.  
  75. printf("plain: %s\n", plaintext);
  76. encrypt(buffer, buffer_len, IV, key, keysize);
  77. printf("Encrypted: "); display(buffer, buffer_len);
  78. decrypt(buffer, buffer_len, IV, key, keysize);
  79. printf("Decrypted: %s\n",buffer);
  80.  
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement