Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <ctype.h>
  4. #include <string.h>
  5. #include <openssl/evp.h>
  6.  
  7. //Pad words not 16 characters long
  8. void pad_word(char *word, int length);
  9.  
  10. int main() {
  11. FILE *key;
  12. unsigned char outBuffer[1024 + EVP_MAX_BLOCK_LENGTH];
  13. int outlen;
  14. int k;
  15. char word[16] = {0};
  16. char plaintext[] = "This is a top secret."; //As specified in task description
  17. int ptlen = strlen(plaintext);
  18. char ciphertext[] = "764aa26b55a4da654df6b19e4bce00f4ed05e09346fb0e762583cb7da2ac93a2";
  19. unsigned char iv[] = "aabbccddeeff00998877665544332211";
  20. key = fopen("words.txt", "r");
  21. //Set up OpenSSL cipher
  22. EVP_CIPHER_CTX ctx;
  23. EVP_CIPHER_CTX_init(&ctx);
  24.  
  25.  
  26. while ( fgets(word, 16, key) ) {
  27.  
  28. int outbuf_len;
  29. k = strlen(word);
  30. word[k-1] = '\0';
  31.  
  32. if (k < 16) {
  33. pad_word(word,16);
  34. }
  35. //Init the cipher with correct cipher type
  36. EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), 0, 0, 0, 1);
  37. //printf("%s\n", word);
  38. //Pass in word to be tested as key with given iv.
  39. EVP_CipherInit_ex(&ctx, 0, 0, word, iv, 1);
  40. //Encrypt plaintext through CipherUpdate function, store in out buffer
  41. if (!EVP_CipherUpdate(&ctx, outBuffer, &outbuf_len, plaintext, ptlen)) {
  42. printf("Error\n");
  43. return 0;
  44. }
  45.  
  46. outlen = outbuf_len;
  47. //printf("%02X\n", outBuffer);
  48. EVP_CipherFinal_ex(&ctx, outBuffer + outlen, &outbuf_len);
  49. outlen += outbuf_len;
  50. //Convert outbuffer to a string (lines 50-58)
  51. int i;
  52. char* string = (char*) malloc(2*outlen + 1);
  53. char* str_ptr = string;
  54.  
  55. for (i = 0; i < outlen; i++) {
  56. str_ptr += sprintf(str_ptr, "%02X", outBuffer[i]);
  57. }
  58. *(str_ptr + 1) = '\0';
  59. //Convert string to lower case
  60. for (int j = 0; j < strlen(string); j++) {
  61. string[j] = tolower(string[j]);
  62. }
  63. // printf("%d\n", outlen);
  64. //printf("%s\n", string);
  65. //Compare plaintext encrypted with padded word to ciphertext, if it
  66. //is the same output the word as correct answer.
  67. if (strcmp(string, ciphertext) == 0) {
  68. printf("%s is a match", word);
  69. return 1;
  70. }
  71. EVP_CIPHER_CTX_cleanup(&ctx); //cleanup
  72. }
  73. fclose(key);
  74. return 1;
  75.  
  76. }
  77. //Pad word as described in task instructions
  78. void pad_word(char *word, int length) {
  79. int wordLen = strlen(word);
  80. while (wordLen < length) {
  81. word[wordLen] = '#';
  82. wordLen++;
  83. }
  84. word[wordLen] = '\0';
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement