Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Шифр_Вернана
- {
- class Program
- {
- static void Main(string[] args)
- {
- var msg = "hello, world";
- var key = "key";
- var rc4 = new RC4(Encoding.ASCII.GetBytes(key));
- var cryptedMsg = rc4.Crypt(Encoding.ASCII.GetBytes(msg));
- Console.WriteLine(Encoding.ASCII.GetString(cryptedMsg));
- var deCryptedMsg = rc4.DeCrypt(cryptedMsg);
- Console.WriteLine(Encoding.ASCII.GetString(deCryptedMsg));
- }
- }
- class RC4
- {
- private byte[] S = new byte[256];
- private byte[] Key;
- public RC4(byte[] key)
- {
- Key = key.Clone() as byte[];
- InitS();
- }
- public RC4()
- {
- for (byte i = 0; i < S.Length; i++) S[i] = i;
- }
- public byte GetNewKey()
- {
- byte i = 0;
- byte j = 0;
- i = (byte)((i + 1) % 256);
- j = (byte)((j + S[i]) % 256);
- Swap(ref S[i], ref S[j]);
- var t = (S[i] + S[j]) % 256;
- return S[t];
- }
- public void InitS()
- {
- for (int i = 0; i < 256; i++) S[i] = (byte)i;
- int j = 0;
- for (int i =0; i <256;i++)
- {
- j = (j + S[i] + Key[i%Key.Length]) % 256;
- Swap(ref S[i], ref S[j]);
- }
- }
- public byte[] Crypt(byte[] arr)=>
- (from item in arr select (byte)(item ^ GetNewKey())).ToArray();
- public byte[] DeCrypt(byte [] msg)
- {
- InitS();
- return Crypt(msg);
- }
- public static void Swap(ref byte left, ref byte right)
- {
- left ^= right;
- right ^= left;
- left ^= right;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement