Advertisement
mrAnderson33

RC4

Jun 7th, 2018
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Шифр_Вернана
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             var msg = "hello, world";
  12.             var key = "key";
  13.    
  14.             var rc4 = new RC4(Encoding.ASCII.GetBytes(key));
  15.  
  16.             var cryptedMsg = rc4.Crypt(Encoding.ASCII.GetBytes(msg));
  17.  
  18.             Console.WriteLine(Encoding.ASCII.GetString(cryptedMsg));
  19.  
  20.             var deCryptedMsg = rc4.DeCrypt(cryptedMsg);
  21.            
  22.             Console.WriteLine(Encoding.ASCII.GetString(deCryptedMsg));
  23.  
  24.         }
  25.  
  26.  
  27.     }
  28.  
  29.     class RC4
  30.     {
  31.         private byte[] S = new byte[256];
  32.  
  33.         private byte[] Key;
  34.  
  35.         public RC4(byte[] key)
  36.         {
  37.             Key = key.Clone() as byte[];
  38.             InitS();
  39.         }
  40.  
  41.         public RC4()
  42.         {
  43.             for (byte i = 0; i < S.Length; i++) S[i] = i;
  44.         }
  45.  
  46.         public byte GetNewKey()
  47.         {
  48.            byte i = 0;
  49.            byte j = 0;
  50.            i = (byte)((i + 1) % 256);
  51.            j = (byte)((j + S[i]) % 256);
  52.            Swap(ref S[i], ref S[j]);
  53.            var t = (S[i] + S[j]) % 256;
  54.            return   S[t];
  55.            
  56.         }
  57.         public void InitS()
  58.         {    
  59.             for (int i = 0; i < 256; i++) S[i] = (byte)i;
  60.  
  61.             int j = 0;
  62.  
  63.             for (int i =0; i <256;i++)
  64.             {
  65.                 j = (j + S[i] + Key[i%Key.Length]) % 256;
  66.                 Swap(ref S[i], ref S[j]);
  67.             }
  68.  
  69.         }
  70.  
  71.         public byte[] Crypt(byte[] arr)=>
  72.           (from item in arr select (byte)(item ^ GetNewKey())).ToArray();
  73.  
  74.         public byte[] DeCrypt(byte [] msg)
  75.         {
  76.             InitS();
  77.             return Crypt(msg);
  78.         }
  79.      
  80.         public static void Swap(ref byte left, ref byte right)
  81.         {
  82.             left ^= right;
  83.             right ^= left;
  84.             left ^= right;
  85.         }
  86.  
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement