C#将字母或数字加密成字母的要领

时间:2022-03-06 08:19:35

public class MD5

{

static List<KeyValuePair<char, char>> MappingList;

#region 加密      public static string Encrypt(string str)

/// <summary>

/// 加密

/// </summary>

/// <param name=”str”>要加密的字符串</param>

/// <returns>返回功效的字符串</returns>

public static string Encrypt(string str)

{

MappingList = new List<KeyValuePair<char, char>>();

for (char c = ‘0’; c <= ‘9’; c++)

MappingList.Add(new KeyValuePair<char, char>(c, (char)(c – ‘0’ + ‘a’)));

for (char c = ‘a’; c <= ‘f’; c++)

MappingList.Add(new KeyValuePair<char, char>(c, (char)(c – ‘a’ + ‘u’)));

return Encoding.ASCII.GetBytes(str)

.Select((b, i) => (b ^ ((byte)(0xa0 + i))).ToString(“x2”))

.Aggregate(“”, (s, c) => s + c)

.ToCharArray().Select(c => MappingList.First(kv => kv.Key == c).Value)

.Aggregate(“”, (s, c) => s + c);

}

#endregion

#region 解密       public static string Decrypt(string str)

/// <summary>

/// 解密

/// </summary>

/// <param name=”str”>解密的字符串</param>

/// <returns>返回功效字符串</returns>

public static string Decrypt(string str)

{

string base16 = str.ToCharArray()

.Select(c => MappingList.First(kv => kv.Value == c).Key)

.Aggregate(“”, (s, c) => s + c);

return Encoding.ASCII.GetString((new byte[base16.Length / 2])

.Select((b, i) => (byte)(Convert.ToByte(base16.Substring(i * 2, 2), 16) ^ ((byte)(0xa0 + i)))).ToArray());

}

#endregion

}