adhokshaj

Simple Encryption/Decryption in C++

Apr 23rd, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. /*
  2.     Program for simple encryption and decryption.
  3.  
  4.     c0d3d by sm@rtw3ap0n
  5. */
  6.  
  7. #include<iostream>
  8. #include<conio.h>
  9. #include<cctype>
  10. #include<cstring>
  11. #include<Windows.h>
  12.  
  13. using namespace std;
  14.  
  15. // read key from user
  16.  
  17. int readkey()
  18. {
  19.     int key=0;
  20.     cout<<"\nEnter key: ";
  21.     // input key through a loop to prevent invalid input
  22.     char ch;
  23.     do
  24.     {
  25.         ch = getche();
  26.         if (isdigit(ch))
  27.         {
  28.             key = key*10 + atoi(&ch);
  29.         }
  30.         else if (ch != 13)
  31.         {
  32.             cout<<"\b";
  33.             Beep(800, 250);
  34.         }
  35.     } while (ch != 13);
  36.  
  37.     return key;
  38. }
  39.  
  40. // encrypt the message
  41.  
  42. void encrypt(int key, char msg[])
  43. {
  44.     int length = strlen(msg);
  45.     int k = key;
  46.     for (int i = length - 1; i >= 0; --i)
  47.     {
  48.         msg[i] += k%10;
  49.         if (msg[i] > 126)
  50.         {
  51.             msg[i] -= 94;
  52.         }
  53.         else if (msg[i] < 32)
  54.         {
  55.             msg[i] += 95;
  56.         }
  57.         if (k%10 == k)
  58.         {
  59.             k = key;
  60.         }
  61.         else
  62.         {
  63.             k /= 10;
  64.         }
  65.     }
  66. }
  67.  
  68. // decrypt the message
  69.  
  70. void decrypt(int key, char msg[])
  71. {
  72.     int length = strlen(msg);
  73.     int k = key;
  74.     for (int i = length - 1; i >= 0; --i)
  75.     {
  76.         msg[i] -= k%10;
  77.         if (msg[i] > 126)
  78.         {
  79.             msg[i] -= 94;
  80.         }
  81.         else if (msg[i] < 32)
  82.         {
  83.             msg[i] += 95;
  84.         }
  85.         if (k%10 == k)
  86.         {
  87.             k = key;
  88.         }
  89.         else
  90.         {
  91.             k /= 10;
  92.         }
  93.     }
  94. }
  95.  
  96. int main()
  97. {
  98.     char msg[100];
  99.     int key;
  100.     cout<<"\nEnter message: ";
  101.     cin.getline(msg, 99);
  102.     key = readkey();
  103.  
  104.     // encrypt it!
  105.     encrypt(key, msg);
  106.     cout<<"\nEncrypted Message: ";
  107.     puts(msg);
  108.  
  109.     // decrypt it!
  110.     decrypt(key, msg);
  111.     cout<<"\n\nDecrypted Message: ";
  112.     puts(msg);
  113.     _getch();
  114.     return 0;
  115. }
Advertisement
Add Comment
Please, Sign In to add comment