异或加密是一种简单而有效的加密技术,它的特点是同一密钥可用于加密和解密,以下是一个例子:
using System;
using System.Text;
public static class Encryption
{
/// <summary>
/// bytes数据通过encryptCode进行异或(加密|解密)
/// 将传入的bytes作为返回值,不再额外分配内存
/// </summary>
/// <param name="bytes"></param>
/// <param name="startIndex"></param>
/// <param name="length"></param>
/// <param name="encrypt"></param>
public static void GetSelfXorBytes(byte[] bytes, int startIndex, int length, byte[] encrypt)
{
int codeIndex = startIndex % encrypt.Length; // 避免codeIndex超上限
for (int i = startIndex; i < startIndex + length; i++)
{
bytes[i] ^= encrypt[codeIndex++];
codeIndex %= encrypt.Length; // 避免codeIndex超上限
}
}
public static void Test()
{
string demo = "Hello World";
string encrypt = "密码本";
byte[] demoBytes = Encoding.UTF8.GetBytes(demo);
byte[] encryptBytes = Encoding.UTF8.GetBytes(encrypt);
GetSelfXorBytes(demoBytes, 0, demoBytes.Length, encryptBytes);
demo = Encoding.UTF8.GetString(demoBytes);
Console.WriteLine(demo);
GetSelfXorBytes(demoBytes, 0, demoBytes.Length, encryptBytes);
demo = Encoding.UTF8.GetString(demoBytes);
Console.WriteLine(demo);
}
}
在该代码中,我们做了点小优化,将加密|解密后数据直接存储在bytes中,避免内存浪费。以下是输出结果: