-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileEncryption.c
More file actions
68 lines (61 loc) · 1.87 KB
/
fileEncryption.c
File metadata and controls
68 lines (61 loc) · 1.87 KB
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
#include <stdio.h>
#include <stdlib.h>
#define BINFILENAME "results.bin"
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Missing 1 or 2 arguments\n");
return 0;
}
const char key = *(argv[1]);
const char* filename = argv[2];
int rc = 0;
FILE *fd = fopen(filename, "r");
// Error checking: Check if file exists or not
if (!fd) {
printf("ERROR: %s does not exist\n", filename);
return -1;
}
// If the file does exist, continue encrypting
// The program calculates the size of the file
fseek(fd, 0, SEEK_END);
unsigned long fsize = ftell(fd);
printf("fsize = %lu\n", fsize);
fseek(fd, 0, SEEK_SET);
// Read the data
char *encryption = (char *) malloc(fsize);
char *encryptionStart = encryption;
if (encryption == NULL) {
printf("ERROR: Cannot malloc encryption\n");
fclose(fd);
return -2;
}
while (1) {
// Read one character using fgetc
char readChar = fgetc(fd);
if (readChar == EOF) {
break;
}
// Encrypt character
char encryptedChar = readChar ^ key;
*encryption++ = encryptedChar;
// Decrypt character
char decryptedChar = encryptedChar ^ key;
// Compare with original
if (decryptedChar != readChar) {
printf("Error: Encryption does not work, readChar = 0x%02x, encryptedChar = 0x%02x, decryptedChar = 0x%02x", readChar, encryptedChar, decryptedChar);
break;
}
} // while (1) {
FILE *binFileDescriptor = fopen(BINFILENAME, "w");
if (!binFileDescriptor) {
printf("ERROR: Cannot open file %s\n", BINFILENAME);
rc = -3;
}
else {
fwrite(encryptionStart, fsize, 1, binFileDescriptor);
}
fclose(binFileDescriptor);
free(encryptionStart);
fclose(fd);
return rc;
}