C# RC4Engine(加密/解密)
RC4是密鑰長度可變的流加密算法簇。其核心部分的S-box長度無限制
,該算法的速度可以達到DES加密的10倍左右,且具有很高級別的非
線性。RC4包括初始化算法(KSA)與偽隨機數生成算法(PRGA)兩個部分。
public static byte[] rc4_init(string key)
{
byte[] box = new byte[255];
for (int i = 0; i < 255; i++)
box[i] = (byte)i;
for (int i = 0, j = 0; i < 255; i++)
{
j = (j + box[i] + key[i % key.Length]) % 255;
byte b = box[i];
box[i] = box[j];
box[j] = b;
}
return box;
}
上面是初始化算法主要隨機打爛S-box中的密鑰序列順序與初始化
Key值。首先定義一個byte[] box緩沖區,然后進行首次的循環,
把S-Box賦入初值,第二次循環進行隨機打爛S-box密鑰序列。
public static string rc4_crypt(string key, string value)
{
byte[] box = rc4_init(key);
char[] buffer = value.ToCharArray();
for (int i = 0, low = 0, high = 0, mid; i < buffer.Length; i++)
{
low = (low + 1) % 255;
high = (high + box[i % 255]) % 255;
byte b = box[low];
box[low] = box[high];
box[high] = b;
mid = (box[low] + box[high]) % 255;
buffer[i] ^= (char)box[mid];
}
return new string(buffer);
}
上面是偽子隨機數生成部分,首先調用rc4_init(key)獲取到
被隨機打爛的密鑰序列S-box,然后通過把value轉換成buffer
緩沖區,我們按照buffer.Length進行計次循環,首先我們需要
計算偽低位索引 low = (low + 1) % 255; 然后計算偽高位索引
high = (high + box[i % 255]) % 255,到了這里我們開始交換
兩者的值,這里為偽隨機數生成部分,下面則通過把兩者所以
的S-box中的值相加% 255取得偽中間索引,與buffer[i] ^= (ch
ar)box[mid]; 進行異或并賦值 最后在把buffer返回給調用方。
這個算法就基本完成了 如如果我解釋的并不是很清楚 你也可以
點開這個鏈接,http://baike.baidu.com/link?url=PpEcozy2oqUap
zng83HJ3-9jknr_qbg-mIUReRYowP215l-RP4R5qEjw8jn0X67QG
M8mJJlAIuEUhtPQNC4QOa
RC4 應用代碼:
public static void Main(string[] args){
string enc = rc4_crypt("China", "Japan"); // 加密
string dec = rc4_crypt("China", enc); // 解密
}