用正则表达式简单加密(C#为例)

时间:2023-02-09 19:46:18
public string Encrypt(string pwd, string key = "0")
    {
        List<string> keys = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        int counter = 0;        if (key != "0")
        {
            foreach (char i in key)
            {
                keys[counter] = i.ToString();
                counter++;
            }
        }
        List<string> secret = new List<string> { "","","","","","","","","","" };
        for(int j = 0; j < 10; j++)
        {
            pwd = Regex.Replace(pwd, keys[j], secret[j]);
        }
        return pwd;
    }

1.首先,新建keys列表作为密匙列表,其中将key(密匙)中字符读入keys中(foreach实现)

2.设定替换字符列表secret,(由于此处加密的是10个数字,且因为密码设定要求需要大小写及数字特殊字符混合,因而加密替换字符用汉字表示)

3.使用正则表达式,通过循环,依次替换数列,此处应注意,每次都应以上一次循环结束后所赋值的pwd作为一个参数,否则无法实现全部替换

至此,加密完成。

解密函数代码如下(原理等同):