Advertisement
SVXX

XOR Encryption in C

Jan 23rd, 2014
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. //#include <conio.h> Need in Windows
  5.  
  6. char* encryption(char* str, char* key)
  7. {
  8.     int i = 0, j = 0;
  9.     char* crypted = (char*) malloc(sizeof(str));
  10.     if(strlen(key) > strlen(str))
  11.     {
  12.         printf("\nThe key cannot be larger than the string itself.");
  13.         return NULL;
  14.     }
  15.     else
  16.     {
  17.         while(str[i] != '\0')
  18.         {
  19.             for(j = 0; j < strlen(key); j++)
  20.             {
  21.                 if(j == (strlen(str)))
  22.                     continue;
  23.                 else
  24.                 {
  25.                     crypted[i] = str[i] ^ key[j];
  26.                     i++;
  27.                 }
  28.             }
  29.         }
  30.     }
  31.     return crypted;
  32. }
  33.  
  34.  
  35. int main()
  36. {
  37.     char str[50], key[50];
  38.     int i = 0;
  39.     char* strptr;
  40.     //clrscr(); Need this in Windows
  41.     printf("Enter the string to be encrypted -: ");
  42.     gets(str);
  43.     printf("\nEnter the key to be used -: ");
  44.     gets(key);
  45.     printf("\nString in hex -: ");
  46.     for(i = 0; str[i] != '\0'; i++)
  47.         printf("%x", str[i]);
  48.     strptr = encryption(str, key);
  49.     if(strptr == NULL)
  50.     {
  51.         printf("\nEncryption failed.\n");
  52.         //getch(); Need this in Windows
  53.         exit(1);
  54.     }
  55.     printf("\nThe encrypted string in hexadecimal is -: ");
  56.     for(i = 0; strptr[i] != '\0'; i++)
  57.         printf("%x", strptr[i]);
  58.     strptr = encryption(strptr, key);
  59.     printf("\nDecrypting -: ");
  60.     for(i = 0; strptr[i] != '\0'; i++)
  61.         printf("%c", strptr[i]);
  62.     printf("\n");
  63.     //getch(); Need this in Windows
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement