Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <openssl/evp.h>
- //Pad words not 16 characters long
- void pad_word(char *word, int length);
- int main() {
- FILE *key;
- unsigned char outBuffer[1024 + EVP_MAX_BLOCK_LENGTH];
- int outlen;
- int k;
- char word[16] = {0};
- char plaintext[] = "This is a top secret."; //As specified in task description
- int ptlen = strlen(plaintext);
- char ciphertext[] = "764aa26b55a4da654df6b19e4bce00f4ed05e09346fb0e762583cb7da2ac93a2";
- unsigned char iv[] = "aabbccddeeff00998877665544332211";
- key = fopen("words.txt", "r");
- //Set up OpenSSL cipher
- EVP_CIPHER_CTX ctx;
- EVP_CIPHER_CTX_init(&ctx);
- while ( fgets(word, 16, key) ) {
- int outbuf_len;
- k = strlen(word);
- word[k-1] = '\0';
- if (k < 16) {
- pad_word(word,16);
- }
- //Init the cipher with correct cipher type
- EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), 0, 0, 0, 1);
- //printf("%s\n", word);
- //Pass in word to be tested as key with given iv.
- EVP_CipherInit_ex(&ctx, 0, 0, word, iv, 1);
- //Encrypt plaintext through CipherUpdate function, store in out buffer
- if (!EVP_CipherUpdate(&ctx, outBuffer, &outbuf_len, plaintext, ptlen)) {
- printf("Error\n");
- return 0;
- }
- outlen = outbuf_len;
- //printf("%02X\n", outBuffer);
- EVP_CipherFinal_ex(&ctx, outBuffer + outlen, &outbuf_len);
- outlen += outbuf_len;
- //Convert outbuffer to a string (lines 50-58)
- int i;
- char* string = (char*) malloc(2*outlen + 1);
- char* str_ptr = string;
- for (i = 0; i < outlen; i++) {
- str_ptr += sprintf(str_ptr, "%02X", outBuffer[i]);
- }
- *(str_ptr + 1) = '\0';
- //Convert string to lower case
- for (int j = 0; j < strlen(string); j++) {
- string[j] = tolower(string[j]);
- }
- // printf("%d\n", outlen);
- //printf("%s\n", string);
- //Compare plaintext encrypted with padded word to ciphertext, if it
- //is the same output the word as correct answer.
- if (strcmp(string, ciphertext) == 0) {
- printf("%s is a match", word);
- return 1;
- }
- EVP_CIPHER_CTX_cleanup(&ctx); //cleanup
- }
- fclose(key);
- return 1;
- }
- //Pad word as described in task instructions
- void pad_word(char *word, int length) {
- int wordLen = strlen(word);
- while (wordLen < length) {
- word[wordLen] = '#';
- wordLen++;
- }
- word[wordLen] = '\0';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement