如果你只做能力范围之内的事,你就永远不会有进步!|

陈侠云

园龄:2年10个月粉丝:1关注:1

使用异或操作实现字符串加密与解密

异或加密是一种简单而有效的加密技术,它的特点是同一密钥可用于加密和解密,以下是一个例子:

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中,避免内存浪费。以下是输出结果:
image

本文作者:陈侠云

本文链接:https://www.cnblogs.com/chenxiayun/p/18440174

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   陈侠云  阅读(82)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起