.NET Base64字符串解码

来源:互联网 发布:vue.js监听输入框变化 编辑:程序博客网 时间:2024/05/16 19:56

public string base64_decode(string strIn)
    {
        int w1;
        int w2;
        int w3;
        int w4;
        string strOut = null;

        for (int n = 0; n <= strIn.Length - 1; n += 4) {
            w1 = mimedecode(strIn.Substring(n, 1));
            if ((n + 1) <= (strIn.Length - 1))
            {

                w2 = mimedecode(strIn.Substring(n + 1, 1));

            }
            else {
                w2 = 0;
            }

            if ((n + 2) <= (strIn.Length - 1))
            {

                w3 = mimedecode(strIn.Substring(n + 2, 1));

            }
            else
            {
                w3 = 0;
            }


            if ((n + 3) <= (strIn.Length - 1))
            {

                w4 = mimedecode(strIn.Substring(n + 3, 1));

            }
            else
            {
                w4 = 0;
            }


            if (w2 >= 0)
                strOut = strOut + (char)((w1 * 4 + Convert.ToInt32(w2 / 16)) & 255);

            if (w3 >= 0)
                strOut = strOut + (char)(((w2 * 16 + Convert.ToInt32(w3 / 4)) & 255));

            if (w4 >= 0)
                strOut = strOut + (char)(((w3 * 64 + w4) & 255));


        }

        return strOut;
   
    }


    public int mimedecode(string strIn)
    {

        string Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                           "abcdefghijklmnopqrstuvwxyz" +
                           "0123456789" + "+/";
        if (strIn.Length == 0)
        {
            return -1;
        }
        else {
            return Base64Chars.IndexOf(strIn);
        }
   
    }

 

base64_decode函数传入一个base64编码的字符串,返回strOut,是一个已解码的字符串