Advertisement
Guest User

rc4.cs

a guest
May 24th, 2015
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. public static class RC4
  7. {
  8.     public static string Encrypt(string key, string data)
  9.     {
  10.         Encoding unicode = Encoding.Unicode;
  11.  
  12.         return Convert.ToBase64String(Encrypt(unicode.GetBytes(key), unicode.GetBytes(data)));
  13.     }
  14.  
  15.     public static string Decrypt(string key, string data)
  16.     {
  17.         Encoding unicode = Encoding.Unicode;
  18.  
  19.         return unicode.GetString(Encrypt(unicode.GetBytes(key), Convert.FromBase64String(data)));
  20.     }
  21.  
  22.     public static byte[] Encrypt(byte[] key, byte[] data)
  23.     {
  24.         return EncryptOutput(key, data).ToArray();
  25.     }
  26.  
  27.     public static byte[] Decrypt(byte[] key, byte[] data)
  28.     {
  29.         return EncryptOutput(key, data).ToArray();
  30.     }
  31.  
  32.     private static byte[] EncryptInitalize(byte[] key)
  33.     {
  34.         byte[] s = Enumerable.Range(0, 256)
  35.             .Select(i => (byte)i)
  36.             .ToArray();
  37.  
  38.         for (int i = 0, j = 0; i < 256; i++)
  39.         {
  40.             j = (j + key[i % key.Length] + s[i]) & 255;
  41.  
  42.             Swap(s, i, j);
  43.         }
  44.  
  45.         return s;
  46.     }
  47.  
  48.     private static IEnumerable<byte> EncryptOutput(byte[] key, IEnumerable<byte> data)
  49.     {
  50.         byte[] s = EncryptInitalize(key);
  51.  
  52.         int i = 0;
  53.         int j = 0;
  54.  
  55.         return data.Select((b) =>
  56.         {
  57.             i = (i + 1) & 255;
  58.             j = (j + s[i]) & 255;
  59.  
  60.             Swap(s, i, j);
  61.  
  62.             return (byte)(b ^ s[(s[i] + s[j]) & 255]);
  63.         });
  64.     }
  65.  
  66.     private static void Swap(byte[] s, int i, int j)
  67.     {
  68.         byte c = s[i];
  69.  
  70.         s[i] = s[j];
  71.         s[j] = c;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement