· 9 years ago · Jan 17, 2017, 09:20 PM
1program main;
2
3(*
4 This program performs XOR operation on input data from standard input and
5 sends to standard output.
6*)
7
8uses
9 SysUtils;
10
11const
12 stdin = 0;
13 stdout = 1;
14 stderr = 2;
15
16const
17 sl = #10;
18 dl = sl+sl;
19
20var
21 fd0 : file of byte;
22 buf0 : ^byte;
23 count_read : sizeint;
24 count_read2: sizeint;
25 secret_key : ^byte;
26 key_len : sizeuint;
27 key_pos : sizeuint;
28 lp0 : sizeuint;
29
30var
31 exe_name: string;
32
33procedure show_help();
34begin
35 Write({$I %DATE%},' - ',{$I %TIME%},' BRT',sl);
36 Write('xor is a program to perform xor operation on files.',dl);
37
38 Write('Usage:',sl);
39 Write('To xor a file:',sl);
40 Write(' cat /path/to/file.data | ',exe_name,' /path/to/key.data',dl);
41
42 Write('Note:',sl);
43 Write(' Key file must be of same length as input data.',sl);
44
45 halt(0);
46end;
47
48begin
49 exe_name := ExtractFileName(ParamStr(0));
50
51 count_read := 0;
52
53 if (ParamCount <> 1) or not (FileExists(ParamStr(1))) then show_help();
54
55 // read key data from file
56 Assign(fd0, ParamStr(1));
57 Reset(fd0);
58
59 secret_key := GetMem(1024*1024);
60 buf0 := GetMem(1024*1024);
61
62 BlockRead(fd0, secret_key^, 1024*1024, count_read);
63
64 key_len := count_read;
65 key_pos := 0;
66
67 repeat
68 count_read2 := FileRead(stdin, buf0^, 1024*1024);
69
70 if count_read2 = 0 then break;
71
72 for lp0 := 0 to count_read2-1 do
73 begin
74 buf0[lp0] := buf0[lp0] xor secret_key[key_pos];
75
76 inc(key_pos);
77
78 if key_pos = key_len then
79 begin
80 BlockRead(fd0, secret_key^, 1024*1024, count_read);
81
82 key_len := count_read;
83 key_pos := 0;
84 end;
85 end;
86
87 FileWrite(stdout, buf0^, count_read2);
88 until 0<>0;
89
90 FreeMem(buf0);
91 FreeMem(secret_key);
92end.