2、C# 编码/加密工具集

1、Base64概念

1.标准base64只有64个字符(英文大小写、数字和+、/)以及用作后缀等号;
2.base64是把3个字节变成4个可打印字符,所以base64编码后的字符串一定能被4整除(不算用作后缀的等号);
3.等号一定用作后缀,且数目一定是0个、1个或2个。这是因为如果原文长度不能被3整除,base64要在后面添加\0凑齐3n位。为了正确还原,添加了几个\0就加上几个等号,
显然添加等号的数目只能是0、1或2; 4.严格来说base64不能算是一种加密,只能说是编码转换。使用base64的初衷。是为了方便把含有不可见字符串的信息用可见字符串表示出来,以便复制粘贴。 作者:郭无心 链接:https://www.zhihu.com/question/36306744/answer/71626823 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
https://www.zhihu.com/question/36306744/answer/71626823

(1)编码

//Base64编码
    public static 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 + "";
    }

(2)解码

 //Base64解码
    public static string DecodeBase64(string code_type, string code)
    {
        if (code == "AA==") return "";
        string decode = "";
        byte[] bytes = Convert.FromBase64String(code);
        try
        {
            decode = Encoding.GetEncoding(code_type).GetString(bytes);
        }
        catch
        {
            decode = code;
        }
        return decode + "";
    }

2、MD5

MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),经MD2、MD3和MD4发展而来。MD5算法的使用不需要支付任何版权费用。

(1)加密

string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(user_psw, "MD5");
//返回16或32位编码
public
static string MD5(string str, int code) { if (code == 16) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16); } if (code == 32) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5"); } return "00000000000000000000000000000000"; }

 

 

 

 

  

posted @ 2017-03-30 19:44  *ち黑サカ  阅读(163)  评论(0编辑  收藏  举报