18 Ağustos 2007 Cumartesi

RC4 Encryption

author: Rick Sands, http://www.bytemycode.com/snippets/snippet/93/
// RC4 Encryption

/*
From RSA Security's website:
"RC4 is a stream cipher designed by Rivest for RSA Data
Security (now RSA Security). It is a variable key-size stream
cipher with byte-oriented operations. The algorithm is based on
the use of a random permutation. Analysis shows that the period
of the cipher is overwhelmingly likely to be greater than 10^100.
Eight to sixteen machine operations are required per output byte,
and the cipher can be expected to run very quickly in software.
Independent analysts have scrutinized the algorithm and it is
considered secure."
This implementation encodes the byte stream to be encrypted
"in-place".
------------
// Examples:
------------
Byte[] Key = new Byte[5] { 12, 34, 22, 12, 32 };
Byte[] B = new Byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Examine B array before and after this next call.
RC4(ref B, Key);
// Examine B array before and after this next call.
RC4(ref B, Key);
*/

public void RC4(ref Byte[] bytes, Byte[] key )
{
Byte[] s = new Byte[256];
Byte[] k = new Byte[256];
Byte temp;
int i, j, t;
int byteLen = bytes.GetLength(0);
int keyLen = key.GetLength(0);

// Generate "8x8 S-Box" and initialize key index
for (i = 0; i < 256; i++)
{
s[i] = (Byte) i;
k[i] = key[i % keyLen];
}

j = 0;
for (i = 0; i<256; i++)
{
j = (j + s[i] + k[i]) % 256;
// swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
}

i = j = 0;
for (int x = 0; x < byteLen; x++)
{
// The following is used to generate a random byte
i = (i + 1) % 256;
j = (j + s[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
t = ((int)s[i] + s[j]) % 256;
// which is xor'd to the source
bytes[x] ^= s[t];
}
}


0 Comments: