C#将字母或数字加密成字母的方法
本文实例讲述了C#将字母或数字加密成字母的方法。分享给大家供大家参考。具体实现方法如下:
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
}
希望本文所述对大家的C#程序设计有所帮助。