/// <summary> /// 维吉尼亚加密与解密 /// </summary> public static class VigenereHelper { /// <summary> /// 密钥 /// </summary> private static string TableKey = @"abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789=&"; /// <summary> /// 生成密钥字符串 /// </summary> /// <param name="input">明文或者密文</param> /// <returns></returns> private static string GetKey(string input) { string key = "ZoveCenter202104091148"; StringBuilder sbKey = new StringBuilder(key); //如果密钥长度比str短,则以不断重复密钥的方式生成密钥字符串 while (sbKey.Length < input.Length) { sbKey.Append(key); } return sbKey.ToString(); } /// <summary> /// 加密算法 /// </summary> /// <param name="input">明文字符串</param> /// <returns>字符串</returns> public static string Encrypt(string input) { //密钥字符串 string K = GetKey(input); StringBuilder sbRel = new StringBuilder(); for (var loop = 0; loop < input.Length; loop++) { //明文字符位置 var iP = TableKey.IndexOf(input[loop]); if (iP == -1) { sbRel.Append(input[loop]); } else { //密钥字符位置 var iK = TableKey.IndexOf(K[loop]); if (iK == -1) { throw new Exception("密钥中包含非法字符:" + TableKey[loop]); } sbRel.Append(TableKey[(iP + iK) % TableKey.Length]); } } return sbRel.ToString(); } /// <summary> /// 解密 /// </summary> /// <param name="input">密文</param> /// <returns>返回解密后的字符串</returns> public static string Decrypt(string input) { //密钥字符串 string K = GetKey(input); StringBuilder sbRel = new StringBuilder(); for (var loop = 0; loop < input.Length; loop++) { //密钥判断 var iK = TableKey.IndexOf(K[loop]); //密文字符 var iC = TableKey.IndexOf(input[loop]); if (iC == -1) { sbRel.Append(input[loop]); } else if (iK > iC) { sbRel.Append(TableKey[iC + TableKey.Length - iK]); } else { sbRel.Append(TableKey[iC - iK]); } } return sbRel.ToString(); } }