quocvuongdn

#Csharp: #RC 4 + Base64

Dec 25th, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. using System.IO;
  2. using System;
  3. using System.Text;
  4.  
  5. class Program
  6. {
  7.     static void Main()
  8.     {
  9.         String input = "data của anh nè";
  10.         String key = "aaa";
  11.         String encryptedStr = Program.Encrypt(input, key);
  12.         String decryptedStr = Program.Decrypt(encryptedStr, key);
  13.         Console.WriteLine("Input string: {0} \nKey: {1}", input, key);
  14.         Console.WriteLine("Encrypted: {0}\nDecrypted: {1}", encryptedStr, decryptedStr);
  15.     }
  16.    
  17.     static string Encrypt(string input, string key){
  18.         byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(input);
  19.         byte[] encrypted = RC4(plainTextBytes, key);
  20.         return System.Convert.ToBase64String(encrypted);
  21.     }
  22.    
  23.     static string Decrypt(string input, string key){
  24.         byte[] base64EncodedBytes = System.Convert.FromBase64String(input);
  25.         byte[] bin = RC4(base64EncodedBytes, key);
  26.         return System.Text.Encoding.UTF8.GetString(bin);
  27.     }
  28.    
  29.     public static byte[] RC4(byte[] data, string pwdKey) {
  30.         int a, i, j, k, tmp;
  31.         int[] key, box;
  32.         byte[] cipher;
  33.    
  34.         key = new int[256];
  35.         box = new int[256];
  36.         cipher = new byte[data.Length];
  37.         byte[] pwd = System.Text.Encoding.UTF8.GetBytes(pwdKey);
  38.    
  39.         for (i = 0; i < 256; i++) {
  40.           key[i] = pwd[i % pwd.Length];
  41.           box[i] = i;
  42.         }
  43.         for (j = i = 0; i < 256; i++) {
  44.           j = (j + box[i] + key[i]) % 256;
  45.           tmp = box[i];
  46.           box[i] = box[j];
  47.           box[j] = tmp;
  48.         }
  49.         for (a = j = i = 0; i < data.Length; i++) {
  50.           a++;
  51.           a %= 256;
  52.           j += box[a];
  53.           j %= 256;
  54.           tmp = box[a];
  55.           box[a] = box[j];
  56.           box[j] = tmp;
  57.           k = box[((box[a] + box[j]) % 256)];
  58.           cipher[i] = (byte)(data[i] ^ k);
  59.         }
  60.         return cipher;
  61.     }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment