Home | History | Annotate | Line # | Download | only in ed
cbc.c revision 1.1
      1 /* cbc.c: This file contains the encryption routines for the ed line editor */
      2 /*-
      3  * Copyright (c) 1991 The Regents of the University of California.
      4  * All rights reserved.
      5  *
      6  * This code is derived from software contributed to Berkeley by
      7  * Matt Bishop of Dartmouth College.
      8  *
      9  * The United States Government has rights in this work pursuant
     10  * to contract no. NAG 2-680 between the National Aeronautics and
     11  * Space Administration and Dartmouth College.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. All advertising materials mentioning features or use of this software
     22  *    must display the following acknowledgement:
     23  *	This product includes software developed by the University of
     24  *	California, Berkeley and its contributors.
     25  * 4. Neither the name of the University nor the names of its contributors
     26  *    may be used to endorse or promote products derived from this software
     27  *    without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     39  * SUCH DAMAGE.
     40  */
     41 
     42 #ifndef lint
     43 static char sccsid[] = "@(#)cbc.c	5.5 (Berkeley) 6/27/91";
     44 #endif /* not lint */
     45 
     46 /* Author: Matt Bishop
     47  *	   Department of Mathematics and Computer Science
     48  *	   Dartmouth College
     49  *	   Hanover, NH  03755
     50  * Email:  Matt.Bishop (at) dartmouth.edu
     51  *	   ...!decvax!dartvax!Matt.Bishop
     52  *
     53  * See Technical Report PCS-TR91-158, Department of Mathematics and Computer
     54  * Science, Dartmouth College, for a detailed description of the implemen-
     55  * tation and differences between it and Sun's.  The DES is described in
     56  * FIPS PUB 46, and the modes in FIPS PUB 81 (see either the manual page
     57  * or the technical report for a complete reference).
     58  */
     59 
     60 #ifdef DES
     61 #include <errno.h>
     62 #include <pwd.h>
     63 #include <unistd.h>
     64 #include <stdio.h>
     65 #include <ctype.h>
     66 #include <stdlib.h>
     67 #include <string.h>
     68 #include <sys/types.h>
     69 
     70 /*
     71  * Define a divisor for rand() that yields a uniform distribution in the
     72  * range 0-255.
     73  */
     74 #define	RAND_DIV (((unsigned) RAND_MAX + 1) >> 8)
     75 
     76 /*
     77  * BSD and System V systems offer special library calls that do
     78  * block moves and fills, so if possible we take advantage of them
     79  */
     80 #define	MEMCPY(dest,src,len)	bcopy((src),(dest),(len))
     81 #define	MEMZERO(dest,len)	bzero((dest),(len))
     82 
     83 /* Hide the calls to the primitive encryption routines. */
     84 #define	DES_KEY(buf) \
     85 	if (des_setkey(buf)) \
     86 		err("des_setkey");
     87 #define	DES_XFORM(buf) \
     88 	if (des_cipher(buf, buf, 0L, (inverse ? -1 : 1))) \
     89 		err("des_cipher");
     90 
     91 /*
     92  * read/write - no error checking
     93  */
     94 #define	READ(buf, n, fp)	fread(buf, sizeof(char), n, fp)
     95 #define WRITE(buf, n, fp)	fwrite(buf, sizeof(char), n, fp)
     96 
     97 /*
     98  * some things to make references easier
     99  */
    100 typedef char Desbuf[8];
    101 #define	CHAR(x,i)	(x[i])
    102 #define	UCHAR(x,i)	(x[i])
    103 #define	BUFFER(x)	(x)
    104 #define	UBUFFER(x)	(x)
    105 
    106 /*
    107  * global variables and related macros
    108  */
    109 
    110 enum { 					/* encrypt, decrypt, authenticate */
    111 	MODE_ENCRYPT, MODE_DECRYPT, MODE_AUTHENTICATE
    112 } mode = MODE_ENCRYPT;
    113 
    114 Desbuf ivec;				/* initialization vector */
    115 Desbuf pvec;				/* padding vector */
    116 char bits[] = {				/* used to extract bits from a char */
    117 	'\200', '\100', '\040', '\020', '\010', '\004', '\002', '\001'
    118 };
    119 int pflag;				/* 1 to preserve parity bits */
    120 
    121 /*
    122  * initialize cbc
    123  */
    124 void
    125 cbcinit()
    126 {
    127 	int i;
    128 
    129 	/* initialize the initialization vctor */
    130 	MEMZERO(ivec, 8);
    131 
    132 	/* intialize the padding vector */
    133 	srand((unsigned) time((time_t *) 0));
    134 	for (i = 0; i < 8; i++)
    135 		CHAR(pvec, i) = (char) (rand()/RAND_DIV);
    136 }
    137 
    138 /*
    139  * get keyword from tty or stdin
    140  */
    141 getkey()
    142 {
    143 	register char *p;		/* used to obtain the key */
    144 	Desbuf msgbuf;			/* I/O buffer */
    145 
    146 	/*
    147 	 * get the key
    148 	 */
    149 	if (*(p = getpass("Enter key: "))) {
    150 
    151 		/*
    152 		 * copy it, nul-padded, into the key area
    153 		 */
    154 		cvtkey(BUFFER(msgbuf), p);
    155 		MEMZERO(p, _PASSWORD_LEN);
    156 		makekey(msgbuf);
    157 		MEMZERO(msgbuf, sizeof msgbuf);
    158 		return 1;
    159 	}
    160 	return 0;
    161 }
    162 
    163 /*
    164  * print a warning message and, possibly, terminate
    165  */
    166 err(s)
    167 	char *s;		/* the message */
    168 {
    169 	(void)fprintf(stderr, "?%s\n", s ? s : strerror(errno));
    170 }
    171 
    172 /*
    173  * map a hex character to an integer
    174  */
    175 tobinhex(c, radix)
    176 	char c;			/* char to be converted */
    177 	int radix;		/* base (2 to 16) */
    178 {
    179 	switch(c) {
    180 	case '0':		return(0x0);
    181 	case '1':		return(0x1);
    182 	case '2':		return(radix > 2 ? 0x2 : -1);
    183 	case '3':		return(radix > 3 ? 0x3 : -1);
    184 	case '4':		return(radix > 4 ? 0x4 : -1);
    185 	case '5':		return(radix > 5 ? 0x5 : -1);
    186 	case '6':		return(radix > 6 ? 0x6 : -1);
    187 	case '7':		return(radix > 7 ? 0x7 : -1);
    188 	case '8':		return(radix > 8 ? 0x8 : -1);
    189 	case '9':		return(radix > 9 ? 0x9 : -1);
    190 	case 'A': case 'a':	return(radix > 10 ? 0xa : -1);
    191 	case 'B': case 'b':	return(radix > 11 ? 0xb : -1);
    192 	case 'C': case 'c':	return(radix > 12 ? 0xc : -1);
    193 	case 'D': case 'd':	return(radix > 13 ? 0xd : -1);
    194 	case 'E': case 'e':	return(radix > 14 ? 0xe : -1);
    195 	case 'F': case 'f':	return(radix > 15 ? 0xf : -1);
    196 	}
    197 	/*
    198 	 * invalid character
    199 	 */
    200 	return(-1);
    201 }
    202 
    203 /*
    204  * convert the key to a bit pattern
    205  */
    206 cvtkey(obuf, ibuf)
    207 	char *obuf;			/* bit pattern */
    208 	char *ibuf;			/* the key itself */
    209 {
    210 	register int i, j;		/* counter in a for loop */
    211 	int nbuf[64];			/* used for hex/key translation */
    212 
    213 	/*
    214 	 * leading '0x' or '0X' == hex key
    215 	 */
    216 	if (ibuf[0] == '0' && (ibuf[1] == 'x' || ibuf[1] == 'X')) {
    217 		ibuf = &ibuf[2];
    218 		/*
    219 		 * now translate it, bombing on any illegal hex digit
    220 		 */
    221 		for (i = 0; ibuf[i] && i < 16; i++)
    222 			if ((nbuf[i] = tobinhex(ibuf[i], 16)) == -1)
    223 				err("bad hex digit in key");
    224 		while (i < 16)
    225 			nbuf[i++] = 0;
    226 		for (i = 0; i < 8; i++)
    227 			obuf[i] =
    228 			    ((nbuf[2*i]&0xf)<<4) | (nbuf[2*i+1]&0xf);
    229 		/* preserve parity bits */
    230 		pflag = 1;
    231 		return;
    232 	}
    233 	/*
    234 	 * leading '0b' or '0B' == binary key
    235 	 */
    236 	if (ibuf[0] == '0' && (ibuf[1] == 'b' || ibuf[1] == 'B')) {
    237 		ibuf = &ibuf[2];
    238 		/*
    239 		 * now translate it, bombing on any illegal binary digit
    240 		 */
    241 		for (i = 0; ibuf[i] && i < 16; i++)
    242 			if ((nbuf[i] = tobinhex(ibuf[i], 2)) == -1)
    243 				err("bad binary digit in key");
    244 		while (i < 64)
    245 			nbuf[i++] = 0;
    246 		for (i = 0; i < 8; i++)
    247 			for (j = 0; j < 8; j++)
    248 				obuf[i] = (obuf[i]<<1)|nbuf[8*i+j];
    249 		/* preserve parity bits */
    250 		pflag = 1;
    251 		return;
    252 	}
    253 	/*
    254 	 * no special leader -- ASCII
    255 	 */
    256 	(void)strncpy(obuf, ibuf, 8);
    257 }
    258 
    259 /*****************
    260  * DES FUNCTIONS *
    261  *****************/
    262 /*
    263  * This sets the DES key and (if you're using the deszip version)
    264  * the direction of the transformation.  This uses the Sun
    265  * to map the 64-bit key onto the 56 bits that the key schedule
    266  * generation routines use: the old way, which just uses the user-
    267  * supplied 64 bits as is, and the new way, which resets the parity
    268  * bit to be the same as the low-order bit in each character.  The
    269  * new way generates a greater variety of key schedules, since many
    270  * systems set the parity (high) bit of each character to 0, and the
    271  * DES ignores the low order bit of each character.
    272  */
    273 makekey(buf)
    274 	Desbuf buf;				/* key block */
    275 {
    276 	register int i, j;			/* counter in a for loop */
    277 	register int par;			/* parity counter */
    278 
    279 	/*
    280 	 * if the parity is not preserved, flip it
    281 	 */
    282 	if (!pflag) {
    283 		for (i = 0; i < 8; i++) {
    284 			par = 0;
    285 			for (j = 1; j < 8; j++)
    286 				if ((bits[j]&UCHAR(buf, i)) != 0)
    287 					par++;
    288 			if ((par&01) == 01)
    289 				UCHAR(buf, i) = UCHAR(buf, i)&0177;
    290 			else
    291 				UCHAR(buf, i) = (UCHAR(buf, i)&0177)|0200;
    292 		}
    293 	}
    294 
    295 	DES_KEY(UBUFFER(buf));
    296 }
    297 
    298 
    299 /*
    300  * This encrypts using the Cipher Block Chaining mode of DES
    301  */
    302 cbcenc(msgbuf, n, fp)
    303 	char *msgbuf;
    304 	int n;
    305 	FILE *fp;
    306 {
    307 	int inverse = 0;	/* 0 to encrypt, 1 to decrypt */
    308 
    309 	/*
    310 	 * do the transformation
    311 	 */
    312 	if (n == 8) {
    313 		for (n = 0; n < 8; n++)
    314 			CHAR(msgbuf, n) ^= CHAR(ivec, n);
    315 		DES_XFORM(UBUFFER(msgbuf));
    316 		MEMCPY(BUFFER(ivec), BUFFER(msgbuf), 8);
    317 		return WRITE(BUFFER(msgbuf), 8, fp);
    318 	}
    319 	/*
    320 	 * at EOF or last block -- in either case, the last byte contains
    321 	 * the character representation of the number of bytes in it
    322 	 */
    323 /*
    324 	MEMZERO(msgbuf +  n, 8 - n);
    325 */
    326 	/*
    327 	 *  Pad the last block randomly
    328 	 */
    329 	(void)MEMCPY(BUFFER(msgbuf + n), BUFFER(pvec), 8 - n);
    330 	CHAR(msgbuf, 7) = n;
    331 	for (n = 0; n < 8; n++)
    332 		CHAR(msgbuf, n) ^= CHAR(ivec, n);
    333 	DES_XFORM(UBUFFER(msgbuf));
    334 	return WRITE(BUFFER(msgbuf), 8, fp);
    335 }
    336 
    337 /*
    338  * This decrypts using the Cipher Block Chaining mode of DES
    339  */
    340 cbcdec(msgbuf, fp)
    341 	char *msgbuf;		/* I/O buffer */
    342 	FILE *fp;			/* input file descriptor */
    343 {
    344 	Desbuf ibuf;	/* temp buffer for initialization vector */
    345 	register int n;		/* number of bytes actually read */
    346 	register int c;		/* used to test for EOF */
    347 	register int bn;	/* block number */
    348 	int inverse = 1;	/* 0 to encrypt, 1 to decrypt */
    349 
    350 	if ((n = READ(BUFFER(msgbuf), 8, fp)) == 8) {
    351 		/*
    352 		 * do the transformation
    353 		 */
    354 		MEMCPY(BUFFER(ibuf), BUFFER(msgbuf), 8);
    355 		DES_XFORM(UBUFFER(msgbuf));
    356 		for (c = 0; c < 8; c++)
    357 			UCHAR(msgbuf, c) ^= UCHAR(ivec, c);
    358 		MEMCPY(BUFFER(ivec), BUFFER(ibuf), 8);
    359 		/*
    360 		 * if the last one, handle it specially
    361 		 */
    362 		if ((c = fgetc(fp)) == EOF) {
    363 			n = CHAR(msgbuf, 7);
    364 			if (n < 0 || n > 7) {
    365 				err("decryption failed (block corrupted)");
    366 				return EOF;
    367 			}
    368 		} else
    369 			(void)ungetc(c, fp);
    370 		return n;
    371 	}
    372 	if (n > 0)
    373 		err("decryption failed (incomplete block)");
    374 	return EOF;
    375 }
    376 #endif	/* DES */
    377