IsraelTorres

ct3-crypto-keys.c

Aug 17th, 2011
249
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  ct3-crypto-keys.c
  3.  Israel Torres hakin9@israeltorres.org
  4.  Sun Aug 14 15:37:12 PDT 2011
  5.  "Cryptotutorials #3 Cryptography fundamentals - Crypto with Keys"
  6.  demo to:
  7.  associate letters to numbers, generate key and encrypt/decrypt w/key
  8.  compile with:
  9.  gcc ct3-crypto-keys.c -o ct3-crypto-keys && ./ct3-crypto-keys
  10.  created and tested on gcc version 4.2.1 / Mac OS X 10.7 11A511
  11.  */
  12.  
  13. #include <time.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <stdlib.h>
  17.  
  18. #define ALPHABET 26 // the size of the alphabet used
  19. #define ALPHAUPP 65 // using ASCII 65-90 for alphabet
  20. #define KEYBUFFR 50 // the size of the keystream
  21.  
  22. int main (int argc, char * argv[])
  23. {
  24.     srand((unsigned)time(NULL)); // seed the 'randomizer'
  25.        
  26.     // test string
  27.     char teststring[]="THESECRETMESSAGE"; int counter=0;
  28.     printf("teststring: [%s]\n",teststring);
  29.     for (;counter < strlen(teststring); counter++){
  30.         printf("%d\t",teststring[counter]-ALPHAUPP);
  31.         printf("%c\n",teststring[counter]);
  32.     }
  33.    
  34.     // genereate pseudo-random keystream
  35.     printf("generating keystream: [");
  36.     int random=0; counter=0; int keystream[KEYBUFFR]={0};
  37.     for (;counter < strlen(teststring); counter++){
  38.         keystream[counter]=rand()%9; // keystream to contain values 0 - 9
  39.         printf("%d",keystream[counter]);
  40.     }
  41.     printf("]\n");
  42.    
  43.     // encrypt test string
  44.     printf("encrypting...\n");
  45.     char encrypted[KEYBUFFR]="\0"; counter=0;
  46.     for (;counter < strlen(teststring); counter++){
  47.         printf("%d\t",teststring[counter]-ALPHAUPP+keystream[counter]);
  48.         encrypted[counter]=teststring[counter]+keystream[counter];
  49.         printf("%c\n",encrypted[counter]);
  50.     }
  51.     printf("encrypted string: [%s]\n",encrypted);
  52.    
  53.     // decrypt encrypted test string
  54.     printf("decrypting...\n");  
  55.     char decrypted[KEYBUFFR]="\0"; counter=0;  
  56.     for (;counter < strlen(encrypted); counter++){
  57.         printf("%d\t",encrypted[counter]-ALPHAUPP-keystream[counter]);
  58.         decrypted[counter]=encrypted[counter]-keystream[counter];
  59.         printf("%c\n",decrypted[counter]);
  60.     }
  61.     printf("decrypted string: [%s]\n",decrypted);
  62.  
  63.     return 0;
  64. }
RAW Paste Data