home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / des2.zip / decrypt.c < prev    next >
Text File  |  1993-03-15  |  2KB  |  75 lines

  1. /* ---------------------- decrypto.c ----------------------- */
  2. /* Single key text file decryption
  3.  * Usage: decrypto keyvalue infile outfile
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <stdlib.h>
  9. #include <process.h>
  10.  
  11. static char decrypt(FILE *);
  12.  
  13. static char *key = NULL;
  14. static int keylen;
  15. static char *cipher = NULL;
  16. static int clen = 0, coff = 0;
  17.  
  18. void main(int argc, char *argv[])
  19. {
  20.    FILE *fi, *fo;
  21.    char ch;
  22.    int runct = 0;
  23.  
  24.    if (argc > 3)    {
  25.        /* --- alloc memory for the key and cipher blocks --- */
  26.        keylen = strlen(argv[1]);
  27.        cipher = malloc(keylen+1);
  28.        key = malloc(keylen+1);
  29.        strcpy(key, argv[1]);
  30.  
  31.        if (cipher != NULL && key != NULL &&
  32.                (fi = fopen(argv[2], "rb")) != NULL)    {
  33.  
  34.            if ((fo = fopen(argv[3], "wb")) != NULL)    {
  35.                while ((ch = decrypt(fi)) != EOF)    {
  36.                    /* --- test for run length counter --- */
  37.                    if (ch & 0x80)
  38.                        runct = ch & 0x7f;
  39.                    else    {
  40.                        if (runct)
  41.                            /* --- run count: dup the byte -- */
  42.                            while (--runct)
  43.                                fputc(ch, fo);
  44.                        fputc(ch, fo);
  45.                    }
  46.                }
  47.                fclose(fo);
  48.            }
  49.            fclose(fi);
  50.        }
  51.        if (cipher)
  52.            free(cipher);
  53.        if (key)
  54.            free(key);
  55.    }
  56. }
  57.  
  58. /* ------ decryption function: returns decrypted byte ----- */
  59. static char decrypt(FILE *fi)
  60. {
  61.    char ch = EOF;
  62.    if (clen == 0)    {
  63.        /* ---- read a block of encrypted bytes ----- */
  64.        clen = fread(cipher, 1, keylen, fi);
  65.        coff = 0;
  66.    }
  67.    if (clen > 0)    {
  68.        /* --- decrypt the next byte in the input block --- */
  69.        ch = *(cipher+coff) ^ *(key+coff);
  70.        coff++;
  71.        --clen;
  72.    }
  73.    return ch;
  74. }
  75.