Public feed #723752

Something

public text v1 · immutable
Raw Edit
·published 2007-10-03 00:32 UTC
rendered paste body
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>

/* Compile with: gcc -O2 -o aescompare aescompare.c -lcrypto */

void printhex(unsigned char *buf16)
{
  int i;
  for (i = 0; i != 16; ++i)
  {
    printf("%02x", buf16[i]);
  }
}

int main(int argc, char *argv[])
{
  FILE *fenc, *fdec, *fkey;
  struct stat fenc_s, fdec_s, fkey_s;
  unsigned char decrypted[16], encrypted[16], decrypted2[16], encrypted2[16], *buf, *buf_lim;
  AES_KEY aes_key;
  int i;

  if (argc != 4)
  {
    fprintf(stderr, "Usage: %s encrypted_file decrypted_file key_file\n", argv[0]);
    return 1;
  }

  fenc = fopen(argv[1], "r");
  fdec = fopen(argv[2], "r");
  fkey = fopen(argv[3], "r");

  if ((fenc == NULL) || (fdec == NULL) || (fkey == NULL))
  {
    perror("fopen");
    return 1;
  }

  if ((fstat(fileno(fenc), &fenc_s) == -1) || (fstat(fileno(fdec), &fdec_s) == -1) || (fstat(fileno(fkey), &fkey_s) == -1))
  {
    perror("fstat");
    return 1;
  }

  if (fenc_s.st_size != fdec_s.st_size)
  {
    fprintf(stderr, "ERROR: Size mismatch between encrypted and decrypted files\n");
    return 1;
  }

  if (fenc_s.st_size & 0xF)
  {
    fprintf(stderr, "ERROR: File size not a multiple of 128 bits\n");
    return 1;
  }

  if (fenc_s.st_size < 32)
  {
    fprintf(stderr, "ERROR: File size smaller than 256 bits\n");
    return 1;
  }

  if (fkey_s.st_size < 16)
  {
    fprintf(stderr, "ERROR: Key file size smaller than 128 bits\n");
    return 1;
  }

  if ((fseek(fenc, -32, SEEK_END) == -1) || (fseek(fdec, -16, SEEK_END) == -1))
  {
    perror("fseek");
    return 1;
  }

  if ((fread(encrypted2, 16, 1, fenc) != 1) || (fread(encrypted, 16, 1, fenc) != 1) || (fread(decrypted, 16, 1, fdec) != 1))
  {
    perror("fread");
    return 1;
  }

  for (i = 0; i != 16; ++i)
    decrypted[i] ^= encrypted2[i];

  printf("Encrypted = ");
  printhex(encrypted);
  printf("\nDecrypted = ");
  printhex(decrypted);
  printf("\nTrying keys...\n");

  buf = (unsigned char *)malloc(fkey_s.st_size);
  if (buf == NULL)
  {
    fprintf(stderr, "ERROR: Out of memory\n");
    return 1;
  }

  if (fread(buf, fkey_s.st_size, 1, fkey) != 1)
  {
    perror("fread");
    return 1;
  }

  buf_lim = buf + fkey_s.st_size - 15;

  do
  {
    AES_set_decrypt_key(buf, 128, &aes_key);
    AES_decrypt(encrypted, decrypted2, &aes_key);
    if (memcmp(decrypted, decrypted2, 16) == 0)
    {
      printf("Score! Key = ");
      printhex(buf);
      printf("\n");
      return 0;
    }
    ++buf;
  } while (buf != buf_lim);
  printf("No suitable key found.\n");

  return 0;
}