C#将字母或数字加密成字母的方法
程序员文章站
2023-12-09 20:18:33
本文实例讲述了c#将字母或数字加密成字母的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:public class md5
{
&nb...
本文实例讲述了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
}
{
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#程序设计有所帮助。