int decrypt_file_ctf()

in reversing/SOMBRERO_ROJO/crypto/rc4block.c [449:531]


int decrypt_file_ctf(char *infile, char *outfile, unsigned char kek[RC4_KEY_BYTES]) 
{
	struct stat st;
	unsigned int fsize = 0;
	unsigned char *input = NULL;
	unsigned char *output;
	rc4ctx decrypted_ctx;

	FILE *fp = fopen(infile, "rb");
	FILE *fo = fopen(outfile, "wb");

	if(fp == 0 || fo == 0){
		#ifdef DEBUG
			printf("File handle problem\n");
		#endif
		return -1;
	}

	stat(infile, &st);
	fsize = st.st_size;

	if(fread(&decrypted_ctx, 1, sizeof(rc4ctx), fp) < 0)
	{
		#ifdef DEBUG
			fprintf(stderr, "fread Error!\n");
		#endif

		fclose(fp);
		fclose(fo);
		return -1;
	}



	if((decrypted_ctx.encrypted_size + sizeof(rc4ctx)) != fsize)
	{
		#ifdef DEBUG
			fprintf(stderr, "Stat file size: %d Encrypted file size: %d\n", fsize, decrypted_ctx.encrypted_size);
			fprintf(stderr, "Decrypted context error esize %d dsize %d padding %d, bool_encrypted %d\n",
			decrypted_ctx.encrypted_size, 
			decrypted_ctx.decrypted_size,
			decrypted_ctx.padding, 
			decrypted_ctx.encrypted);
		#endif 
		fclose(fp);
		fclose(fo);
		return -1;
	}

	input = (unsigned char *) calloc(decrypted_ctx.encrypted_size, sizeof(unsigned char));

	if(input == NULL)
	{
		#ifdef DEBUG
			fprintf(stderr, "Memory Error!");
		#endif
		fclose(fp);
		fclose(fo);
		return -1;
	}

	if(fread(input, sizeof(unsigned char), decrypted_ctx.encrypted_size, fp) < 0)
	{
		#ifdef DEBUG
			fprintf(stderr, "fread Error!\n");
		#endif 
		fclose(fp);
		fclose(fo);
		return -1;
	}
	#ifdef DEBUG
    	printf("Input data bytes: ->");
    	pretty_print_bytes(input, 64);
    #endif 
	output = rc4_block_decrypt_ctf(&decrypted_ctx, input, kek);

	fwrite(output, sizeof(unsigned char), decrypted_ctx.decrypted_size, fo);

	fclose(fo);
	fclose(fp);

return 0;
}