109 lines
3.0 KiB
C#
109 lines
3.0 KiB
C#
using System;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace BF
|
|
{
|
|
/// <summary>
|
|
/// rc4流式加密解密
|
|
/// 加密是连续的,加密完成之后再解密
|
|
/// 速度快,可以用在协议或日志
|
|
/// </summary>
|
|
public class Rc4Encrypt
|
|
{
|
|
private byte[] keyStream;
|
|
public string Key
|
|
{
|
|
set
|
|
{
|
|
keyStream = Encoding.UTF8.GetBytes(value);
|
|
}
|
|
}
|
|
|
|
private byte[] Encrypt(byte[] pwd, byte[] data)
|
|
{
|
|
if (ReferenceEquals(pwd, null))
|
|
{
|
|
return data;
|
|
}
|
|
if (pwd.Length <= 0 || data.Length <= 0)
|
|
{
|
|
return data;
|
|
}
|
|
int a, i, j, k, tmp;
|
|
int[] key, box;
|
|
byte[] cipher;
|
|
|
|
key = new int[256];
|
|
box = new int[256];
|
|
cipher = new byte[data.Length];
|
|
|
|
for (i = 0; i < 256; i++) {
|
|
key[i] = pwd[i % pwd.Length];
|
|
box[i] = i;
|
|
}
|
|
for (j = i = 0; i < 256; i++) {
|
|
j = (j + box[i] + key[i]) % 256;
|
|
tmp = box[i];
|
|
box[i] = box[j];
|
|
box[j] = tmp;
|
|
}
|
|
for (a = j = i = 0; i < data.Length; i++) {
|
|
a++;
|
|
a %= 256;
|
|
j += box[a];
|
|
j %= 256;
|
|
tmp = box[a];
|
|
box[a] = box[j];
|
|
box[j] = tmp;
|
|
k = box[((box[a] + box[j]) % 256)];
|
|
cipher[i] = (byte)(data[i] ^ k);
|
|
}
|
|
return cipher;
|
|
}
|
|
|
|
private byte[] Decrypt(byte[] pwd, byte[] data) {
|
|
return Encrypt(pwd, data);
|
|
}
|
|
|
|
// public static string EncryptBytes(byte[] data, bool toBase64 = false)
|
|
// {
|
|
// byte[] encryptData = Encrypt(keyStream, data);
|
|
//
|
|
// var r = toBase64
|
|
// ? Convert.ToBase64String(encryptData)
|
|
// : Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(Convert.ToBase64String(encryptData)));
|
|
//
|
|
// return r;
|
|
// }
|
|
|
|
// public static string DecryptBytes(byte[] data)
|
|
// {
|
|
// return Encoding.UTF8.GetString(Decrypt(keyStream, data));
|
|
// }
|
|
|
|
public byte[] EncryptBytes(byte[] bytes)
|
|
{
|
|
return Encrypt(keyStream, bytes);
|
|
}
|
|
|
|
public byte[]DecryptBytes(byte[] bytes)
|
|
{
|
|
return Decrypt(keyStream, bytes);
|
|
}
|
|
|
|
public byte[] EncryptStr(string data)
|
|
{
|
|
byte[] bytes = Encoding.UTF8.GetBytes(data);
|
|
return Encrypt(keyStream, bytes);
|
|
}
|
|
|
|
public byte[] DecryptStr(string data)
|
|
{
|
|
byte[] bytes = Encoding.UTF8.GetBytes(data); //Convert.FromBase64String(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(data)));
|
|
return Decrypt(keyStream, bytes);
|
|
}
|
|
}
|
|
} |