SHARE
TWEET

13. Strings and Text Processing 7. Encrypt

Assi Jan 24th, 2013 592 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Text;
  3.  
  4. class EncryptDecrypt
  5. {
  6.     static void Main()
  7.     {
  8.         string str = "Some text for crypting and decrypting!";
  9.         string key = "The key";
  10.  
  11.         Console.Write("Encrypted =>    ");
  12.         string encrypted = Encrypt(str, key);
  13.         Console.WriteLine(encrypted);
  14.  
  15.         Console.Write("Decrypted =>   ");
  16.         string deCrypt = DeCrypt(encrypted, key);
  17.         Console.WriteLine(deCrypt);
  18.     }
  19.     static string Encrypt(string str, string key)
  20.     {
  21.         char[] strArr = str.ToCharArray();
  22.         char[] keyArr = new char[strArr.Length];
  23.  
  24.         StringBuilder encrypted = new StringBuilder();
  25.  
  26.         for (int i = 0, k = 0; i < keyArr.Length; k++, i++)
  27.         {
  28.             if (!(k < key.Length))
  29.             {
  30.                 k = 0;
  31.             }
  32.             keyArr[i] = key[k];
  33.         }
  34.         for (int i = 0; i < strArr.Length; i++)
  35.         {
  36.             encrypted.Append((char)(strArr[i] ^ keyArr[i]));
  37.         }
  38.         return encrypted.ToString();
  39.     }
  40.     static string DeCrypt(string str, string key)
  41.     {
  42.         return Encrypt(str, key).ToString();
  43.     }
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top