xref: /csrg-svn/old/crypt/crypt.c (revision 994)
1*994Sbill static char *sccsid = "@(#)crypt.c	4.1 (Berkeley) 10/01/80";
2*994Sbill /*
3*994Sbill  *	A one-rotor machine designed along the lines of Enigma
4*994Sbill  *	but considerably trivialized.
5*994Sbill  */
6*994Sbill 
7*994Sbill #define ECHO 010
8*994Sbill #include <stdio.h>
9*994Sbill #define ROTORSZ 256
10*994Sbill #define MASK 0377
11*994Sbill char	t1[ROTORSZ];
12*994Sbill char	t2[ROTORSZ];
13*994Sbill char	t3[ROTORSZ];
14*994Sbill char	*getpass();
15*994Sbill 
16*994Sbill setup(pw)
17*994Sbill char *pw;
18*994Sbill {
19*994Sbill 	int ic, i, k, temp, pf[2];
20*994Sbill 	unsigned random;
21*994Sbill 	char buf[13];
22*994Sbill 	long seed;
23*994Sbill 
24*994Sbill 	strncpy(buf, pw, 8);
25*994Sbill 	while (*pw)
26*994Sbill 		*pw++ = '\0';
27*994Sbill 	buf[8] = buf[0];
28*994Sbill 	buf[9] = buf[1];
29*994Sbill 	pipe(pf);
30*994Sbill 	if (fork()==0) {
31*994Sbill 		close(0);
32*994Sbill 		close(1);
33*994Sbill 		dup(pf[0]);
34*994Sbill 		dup(pf[1]);
35*994Sbill 		execl("/usr/lib/makekey", "-", 0);
36*994Sbill 		execl("/lib/makekey", "-", 0);
37*994Sbill 		exit(1);
38*994Sbill 	}
39*994Sbill 	write(pf[1], buf, 10);
40*994Sbill 	wait((int *)NULL);
41*994Sbill 	if (read(pf[0], buf, 13) != 13) {
42*994Sbill 		fprintf(stderr, "crypt: cannot generate key\n");
43*994Sbill 		exit(1);
44*994Sbill 	}
45*994Sbill 	seed = 123;
46*994Sbill 	for (i=0; i<13; i++)
47*994Sbill 		seed = seed*buf[i] + i;
48*994Sbill 	for(i=0;i<ROTORSZ;i++)
49*994Sbill 		t1[i] = i;
50*994Sbill 	for(i=0;i<ROTORSZ;i++) {
51*994Sbill 		seed = 5*seed + buf[i%13];
52*994Sbill 		random = seed % 65521;
53*994Sbill 		k = ROTORSZ-1 - i;
54*994Sbill 		ic = (random&MASK)%(k+1);
55*994Sbill 		random >>= 8;
56*994Sbill 		temp = t1[k];
57*994Sbill 		t1[k] = t1[ic];
58*994Sbill 		t1[ic] = temp;
59*994Sbill 		if(t3[k]!=0) continue;
60*994Sbill 		ic = (random&MASK) % k;
61*994Sbill 		while(t3[ic]!=0) ic = (ic+1) % k;
62*994Sbill 		t3[k] = ic;
63*994Sbill 		t3[ic] = k;
64*994Sbill 	}
65*994Sbill 	for(i=0;i<ROTORSZ;i++)
66*994Sbill 		t2[t1[i]&MASK] = i;
67*994Sbill }
68*994Sbill 
69*994Sbill main(argc, argv)
70*994Sbill char *argv[];
71*994Sbill {
72*994Sbill 	register i, n1, n2;
73*994Sbill 
74*994Sbill 	if (argc != 2){
75*994Sbill 		setup(getpass("Enter key:"));
76*994Sbill 	}
77*994Sbill 	else
78*994Sbill 		setup(argv[1]);
79*994Sbill 	n1 = 0;
80*994Sbill 	n2 = 0;
81*994Sbill 
82*994Sbill 	while((i=getchar()) >=0) {
83*994Sbill 		i = t2[(t3[(t1[(i+n1)&MASK]+n2)&MASK]-n2)&MASK]-n1;
84*994Sbill 		putchar(i);
85*994Sbill 		n1++;
86*994Sbill 		if(n1==ROTORSZ) {
87*994Sbill 			n1 = 0;
88*994Sbill 			n2++;
89*994Sbill 			if(n2==ROTORSZ) n2 = 0;
90*994Sbill 		}
91*994Sbill 	}
92*994Sbill }
93