using System;
namespace NewLife.Security
{
class RC4
{
public static Byte[] Encrypt(Byte[] data, Byte[] pass)
{
if (data == null || data.Length == 0) return new Byte[0];
if (pass == null || pass.Length == 0) return data;
var output = new Byte[data.Length];
var i = 0;
var j = 0;
var box = GetKey(pass, 256);
for (var k = 0; k < data.Length; k++)
{
i = (i + 1) % box.Length;
j = (j + box[i]) % box.Length;
var temp = box[i];
box[i] = box[j];
box[j] = temp;
var a = data[k];
var b = box[(box[i] + box[j]) % box.Length];
output[k] = (Byte)(a ^ b);
}
return output;
}
private static Byte[] GetKey(Byte[] pass, Int32 len)
{
var box = new Byte[len];
for (var i = 0; i < len; i++)
{
box[i] = (Byte)i;
}
var j = 0;
for (var i = 0; i < len; i++)
{
j = (j + box[i] + pass[i % pass.Length]) % len;
var temp = box[i];
box[i] = box[j];
box[j] = temp;
}
return box;
}
}
}
|