C # rc4 algorithm, encryption and decryption class,
Rc4 ..
1/* 2 * created by SharpDevelop. 3 * User: YISH 4 * Date: 04/04/2015 5 * Time: 6*7 * Click Tools to change this template | options | code writing | edit standard header file 8 */9 using System; 10 11 namespace Libraries 12 {13 // <summary> 14 // Description of CryptoGraphy. 15 /// </summary> 16 public class RC4Crypt: IDisposable {17 byte [] S; 18 byte [] T; 19 byte [] K; 20 byte [] k; 21 public RC4Crypt () {}22 public RC4Crypt (byte [] key) {23 this. K = key; 24} 25 public byte [] Key 26 {27 get 28 {29 return K; 30} 31 set 32 {33 K = value; 34} 35} 36 // initialize state vector S and temporary vector T, for keyStream method call 37 void initial () {38 if (S = null | T = null) 39 {40 S = new byte [256]; 41 T = new byte [256]; 42} 43 for (int I = 0; I <256; ++ I) {44 S [I] = (byte) I; 45 T [I] = K [I % K. length]; 46} 47} 48 // The initial permutation state vector S, which is used by the keyStream method to call 49 void ranges () {50 int j = 0; 51 for (int I = 0; I <256; ++ I) {52 j = (j + S [I] + T [I]) & 0xff; 53 S [I] = (byte) (S [I] + S [j]) & 0xff ); 54 S [j] = (byte) (S [I]-S [j]) & 0xff); 55 S [I] = (byte) (S [I]-S [j]) & 0xff); 56} 57} 58 // generate a dense stream 59 // len: the plaintext is 60 void keyStream (int len) {61 initial (); 62 ranges (); 63 int I = 0, j = 0, t = 0; 64 k = new byte [len]; 65 for (int r = 0; r <len; r ++) {66 I = (I + 1) & 0xff; 67 j = (j + S [I]) & 0xff; 68 69 S [I] = (byte) (S [I] + S [j]) & 0xff ); 70 S [j] = (byte) (S [I]-S [j]) & 0xff); 71 S [I] = (Byte) (S [I]-S [j]) & 0xff); 72 73 t = (S [I] + S [j]) & 0xff; 74 k [r] = S [t]; 75} 76} 77 78 public byte [] EncryptByte (byte [] data) {79 // generate the key stream 80 keyStream (data. length); 81 for (int I = 0; I <data. length; I ++) {82 k [I] = (byte) (data [I] ^ k [I]); 83} 84 return k; 85} 86 87 public byte [] DecryptByte (byte [] data) {88 return EncryptByte (data); 89} 90 91 // whether 92 bool _ disposed has been recycled; 93 public void Dispose () 94 {95 Dispose (true); 96 GC. SuppressFinalize (this); 97} 98 ~ RC4Crypt () 99 {100 Dispose (false); 101} 102 // The parameter table here shows whether to release the hosted object 103 protected virtual void Dispose (bool disposing) that implements the IDisposable Interface) 104 {105 if (_ disposed) return; // if it has been recycled, the execution of 106 if (disposing) 107 {108 // TODO: release the managed objects that implement the IDisposable interface 109 110} 111 // TODO: Release the unmanaged resources and set the object to null112 S = null; 113 T = null; 114 K = null; 115 k = null; 116 _ disposed = true; 117} 118} 119}