异或加密是一种简单而有效的加密技术,它的特点是同一密钥可用于加密和解密,以下是代码示例:
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="encryptCode"></param>public static void GetSelfXorBytes(byte[] bytes, int startIndex, int length, byte[] encrypt){int codeLength = encrypt.Length;int codeIndex = startIndex % codeLength;for (int i = startIndex; i < startIndex + length; i++){bytes[i] ^= encrypt[codeIndex++];codeIndex %= codeLength;}}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作为加密|解密后的结果。调用Text()函数,我们可以得到如下结果: