.net的加密解密方法

编码
public string EncodeBase64(string code_type,string code)
  {
   string encode = "";
   byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
   try
   {
    encode = Convert.ToBase64String(bytes);
   }
   catch
   {
    encode = code;
   }
   return encode;
  }
解码
public string DecodeBase64(string code_type,string code)
  {
   string decode = "";
   byte[] bytes = Convert.FromBase64String(code);
   try
   {
    decode = Encoding.GetEncoding(code_type).GetString(bytes);
   }
   catch
   {
    decode = code;
   }
   return decode;
  }

再附上MD5的加密方法
System.Web.Security;
FormsAuthentication.HashPasswordForStoringInConfigFile(toCryString, "MD5")


code_typer的选择
GetEncoding 方法依赖于基础平台支持大部分代码页。但是,对于下列情况提供系统支持:默认编码,即在执行此方法的计算机的区域设置中指定的编码;Little-Endian Unicode (UTF-16LE);Big-Endian Unicode (UTF-16BE);Windows 操作系统 (windows-1252);UTF-7;UTF-8;ASCII 以及 GB18030(简体中文)。

指定下表中列出的其中一个名称以获取具有对应代码页的系统支持的编码。

代码页 名称
“UTF-16LE”、“utf-16”、“ucs-2”、“unicode”或“ISO-10646-UCS-2”
“UTF-16BE”或“unicodeFFFE”
“windows-1252”
“utf-7”、“csUnicode11UTF7”、“unicode-1-1-utf-7”、“unicode-2-0-utf-7”、“x-unicode-1-1-utf-7”或“x-unicode-2-0-utf-7”
“utf-8”、“unicode-1-1-utf-8”、“unicode-2-0-utf-8”、“x-unicode-1-1-utf-8”或“x-unicode-2-0-utf-8”
“us-ascii”、“us”、“ascii”、“ANSI_X3.4-1968”、“ANSI_X3.4-1986”、“cp367”、“csASCII”、“IBM367”、“iso-ir-6”、“ISO646-US”或“ISO_646.irv:1991”
“GB18030”

某些平台可能不支持特定的代码页。例如,Windows 98 的美国版本可能不支持日语 Shift-jis 代码页(代码页 932)。这种情况下,GetEncoding 方法将在执行下面的 C# 代码时引发 NotSupportedException:

Encoding enc = Encoding.GetEncoding("shift-jis"); 

在应用程序中如下:
  public static string GetMD5(Stream stream)
  {
   const string HEX_TABLE = "0123456789ABCDEF";
   MD5 md5 = new MD5CryptoServiceProvider();
   //Calculate MD5 Checksum
   byte[]data = md5.ComputeHash(stream);
   //convert to string
   StringBuilder sb=new StringBuilder();
   sb.Length =data.Length *2;
   for(int i=0;i<data.Length ;i++)
   {
    sb[i*2]=HEX_TABLE[data[i]>>4];
    sb[i*2+1]=HEX_TABLE[data[i] & 0xF];
   }
   return sb.ToString();
  }
  public static string GetMD5(string s)
  {
   byte[] data=ASCIIEncoding.ASCII.GetBytes(s);
   MemoryStream stream=new MemoryStream(data);
   //stream.Write(data,0,data.Length);
   return GetMD5(stream);
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值