home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume29 / libdes / part01 / enc_write.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-04-04  |  1.6 KB  |  85 lines

  1. /* des_enc_write */
  2. /* Copyright (C) 1992 Eric Young - see COPYING for more details */
  3. #include <errno.h>
  4. #include "des_local.h"
  5.  
  6. int des_enc_write(fd,buf,len,sched,iv)
  7. int fd;
  8. char *buf;
  9. int len;
  10. des_key_schedule sched;
  11. des_cblock *iv;
  12.     {
  13.     long l,rnum;
  14.     int i,j,k;
  15.     char outbuf[BSIZE];
  16.     char shortbuf[8];
  17.     char *p;
  18.     static int start=1;
  19.  
  20.     /* If we are sending less than 8 bytes, the same char will look
  21.      * the same if we don't pad it out with random bytes */
  22.     if (start)
  23.         {
  24.         start=0;
  25.         srandom(time(NULL));
  26.         }
  27.  
  28.     /* lets recurse if we want to send the data in small chunks */
  29.     if (len > MAXWRITE)
  30.         {
  31.         j=0;
  32.         for (i=0; i<len; i+=k)
  33.             {
  34.             k=des_enc_write(fd,&(buf[i]),
  35.                 ((len-i) > MAXWRITE)?MAXWRITE:(len-i),sched,iv);
  36.             if (k < 0)
  37.                 return(k);
  38.             else
  39.                 j+=k;
  40.             }
  41.         return(j);
  42.         }
  43.  
  44.     /* pad short strings */
  45.     if (len < 8)
  46.         {
  47.         p=shortbuf;
  48.         bcopy(buf,shortbuf,len);
  49.         for (i=len; i<8; i++)
  50.             shortbuf[i]=random();
  51.         rnum=8;
  52.         }
  53.     else
  54.         {
  55.         p=buf;
  56.         rnum=((len+7)/8*8); /* round up to nearest eight */
  57.         }
  58.  
  59.     /* write length first */
  60.     l=htonl(len);
  61.     bcopy(&l,outbuf,sizeof(long));
  62.     if (des_rw_mode == DES_PCBC_MODE)
  63.         pcbc_encrypt((des_cblock *)p,(des_cblock *)&(outbuf[4]),
  64.             (long)((len<8)?8:len),sched,iv,DES_ENCRYPT); 
  65.     else
  66.         cbc_encrypt((des_cblock *)p,(des_cblock *)&(outbuf[4]),
  67.             (long)((len<8)?8:len),sched,iv,DES_ENCRYPT); 
  68.  
  69.     /* output */
  70.     for (j=0; j<rnum+4; j+=i)
  71.         {
  72.         i=write(fd,outbuf,(int)(rnum+4));
  73.         if (i == -1)
  74.             {
  75.             if (errno == EINTR)
  76.                 i=0;
  77.             else     /* This is really a bad error - very bad
  78.                  * It will stuff-up both ends. */
  79.                 return(-1);
  80.             }
  81.         }
  82.  
  83.     return(len);
  84.     }
  85.