-
Notifications
You must be signed in to change notification settings - Fork 2
/
zeecode.c
121 lines (95 loc) · 2.27 KB
/
zeecode.c
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
* Encryption/Decrytion program based on crypt but uses A0 and Zee
* rather than Rotor and Reflector.
*
* Robert W. Baldwin, December 1984.
*/
#include <stdio.h>
#include <stdlib.h>
#define BLOCKSIZE 256
#define MODMASK (BLOCKSIZE-1)
#define FALSE 0
#define TRUE 1
/* Forward declarations */
void readblock(FILE *fd, int buf[]);
int doblock(int p[]);
void pgate(int *inperm, int *outperm, int *z, int *zi);
/* Global state. */
int perm[BLOCKSIZE]; /* Current A permutation. */
int nxtperm[BLOCKSIZE]; /* Next A permutation. */
int zee[BLOCKSIZE]; /* Zee permutation. */
int zeeinv[BLOCKSIZE]; /* Inverse of Zee permutation. */
char *permfile = "zeecode.perm";
/* Do the deed.
*/
int main(void)
{
int i;
FILE *fd;
if ((fd = fopen(permfile, "r")) == NULL) {
printf("\nCould not open %s to read permutations.\n", permfile);
exit(0);
}
readblock(fd, zee);
for (i = 0 ; i < BLOCKSIZE ; i++) zeeinv[zee[i]] = i;
readblock(fd, perm);
fclose(fd);
while (doblock(perm)) {
pgate(perm, nxtperm, zee, zeeinv);
for (i = 0 ; i < BLOCKSIZE ; i++) perm[i] = nxtperm[i];
}
return 0;
}
/* Compute the permutation after inperm using z and its inverse zi.
* The result is placed in outperm.
*/
void pgate(int *inperm, int *outperm, int *z, int *zi)
{
int i,x,v;
int w;
for (i = 0 ; i < BLOCKSIZE ; i++) {
w = -1;
x = z[i];
if (x != -1) {
v = inperm[x&MODMASK];
if (v != -1)
w = zi[v&MODMASK];
}
outperm[i] = w;
}
}
/* Read character from stdin, encrypt them with the given permutation, p,
* and write them to stdout.
* Return FALSE if reach end of file.
*/
int doblock(int p[])
{
int pos;
int sc;
int c;
for (pos = 0 ; pos < BLOCKSIZE ; pos++) {
if ((c=getchar()) == EOF) return(FALSE);
sc = p[MODMASK&(c+pos)];
if (sc == -1) {putchar('?');}
else {putchar(MODMASK & (sc - pos));}
}
return(TRUE);
}
/* Read a block of BLOCKSIZE integers into the given buffer from
* the given stream.
* The block is terminated by a newline character.
*/
void readblock(FILE *fd, int buf[])
{
int i;
for (i = 0 ; i < BLOCKSIZE ; i++) {
if (fscanf(fd, "%3d ", &buf[i]) != 1) {
printf("\nReadblock error on i = %d\n", i);
exit(0);
}
}
if (fscanf(fd, "\n") != 0) {
printf("\nReadblock error on newline\n");
exit(0);
}
}