cryptest

Cryptography-related scribbles
git clone git://git.finwo.net/misc/cryptest
Log | Files | Refs | README

encrypt.c (1468B)


      1 #ifdef __cplusplus
      2 extern "C" {
      3 #endif
      4 
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <time.h>
      8 
      9 #include "base.h"
     10 
     11 int encrypt( unsigned int mult, unsigned int modulo, unsigned int padding ) {
     12 
     13   // Initialize variables
     14   unsigned long long seed     = 0;
     15   unsigned long long ibuf     = 0;
     16   int flags = 2; // 1=running, 2=input
     17   int c,e, ibuf_len = 0;
     18 
     19   // Randomize the 'rand' call
     20   srandom((unsigned)time(NULL));
     21   for( seed = 5000; seed; rand(), seed-- );
     22 
     23   // Ensure padding
     24   while( padding-- ) {
     25     if ( flags & 1 ) {
     26       seed = seed * mult;
     27       seed = seed % modulo;
     28       seed = seed ^ ( random() % 256 );
     29       fputc( seed % 256, stdout );
     30     } else {
     31       seed = random() % 256;
     32       fputc( seed, stdout );
     33       flags |= 1;
     34     }
     35   }
     36 
     37   // Start encoding
     38   while( flags & 1 ) {
     39 
     40     // Handle stdin
     41     if ( ( flags & 2 ) && ( ibuf_len < 7 ) ) {
     42       if ( (c=fgetc(stdin)) == EOF ) {
     43         flags &= ~2;
     44       } else {
     45         ibuf = ibuf % ( 1 << ibuf_len );
     46         ibuf = ibuf << 8;
     47         ibuf |= c;
     48         ibuf_len += 8;
     49       }
     50     }
     51 
     52     // Fetch number to encode
     53     c = ((ibuf<<7)>>ibuf_len)%128;
     54     ibuf_len -= 7;
     55 
     56     // Feedback-based encoding
     57     e = 0;
     58     seed = seed * mult;
     59     while( ((seed+e)%modulo)%128 != c ) e++;
     60     seed = (seed+e)%modulo;
     61     fputc( e, stdout );
     62 
     63     // EOF detection
     64     if( ibuf_len <= 0 && !(flags&2) ) {
     65       flags &= ~1;
     66     }
     67   }
     68 
     69   return 0;
     70 }
     71 
     72 #ifdef __cplusplus
     73 } // extern "C"
     74 #endif