summaryrefslogtreecommitdiff
path: root/decrypt.c
blob: 305e1ed02c00f60829e7b8c12a10ec74c2cdd9b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
 * SimpleCrypt
 * Non-ECB version
 * So simple it's all one function.
 *
 * Nathan Lasseter (User_4574)
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {

	// We need a file to encrypt
	if (argc != 2) {
		fprintf(stderr, "Usage: encrypt <file>\n");
		return EXIT_FAILURE;
	}

	// Now lets open that file
	FILE* file = fopen(argv[1], "r");
	if (file == NULL) {
		fprintf(stderr, "No such file\n");
		return EXIT_FAILURE;
	}

	// Now we need the passphrase. Get it
	char *passphrase = malloc(256);
	do {
		printf("Enter Passphrase: ");
		if (fgets(passphrase, 255, stdin) == NULL) {
			fclose(file);
			fprintf(stderr, "Read error or end of file\n");
			return EXIT_FAILURE;
		}
	} while (strlen(passphrase) <= 0);

	// And a temporary file to hold the encrypted data
	char tpath[] = ".SimCr.XXXXXX";
	int tempfd = mkstemp(tpath);
	FILE* temp = fdopen(tempfd, "w");

	// Now we decrypt!
	int passlen = strlen(passphrase) - 2;
	int c, d, j = 0;

	while ((c=fgetc(file)) != EOF) {
		d = c - passphrase[j];
		passphrase[j] = c;
		fputc(d, temp);

		if (j == passlen) j=0;
		else j++;
	}

	// Close the files
	fflush(temp);
	fclose(temp);
	fclose(file);

	// Free used memory
	free(passphrase);

	// Move the file back
	if (rename(tpath, argv[1]) != 0) {
		fprintf(stderr, "Your encrypted file is located in %s.", tpath);
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}