FromBase64String(String)和Encoding.Default.GetBytes(String)

今天突然被问FromBase64String(String)和Encoding.Default.GetBytes(String)有啥区别,我刚开始学C#对这个一脸懵逼,于是总结一下今天查资料的内容。

首先,什么是Base64?
Base64呀,是个加密算法,原理呢在这里不重要,以后有机会补充,这里仅举例。
最初明文:abc——>Base64加密——>密文:YWJj ——>Base64加密——>密文:WVdKag== ——>Base64加密——>密文:V1ZkS2FnJTNEJTNE

密文:V1ZkS2FnJTNEJTNE——>Base64解密——>明文:WVdKag==——>Base64加密——>明文:YWJj——>Base64加密——>最初明文:abc

至此还原成功,可见Base64加密不是一对一的,而且多次加密可以由多次解密还原。

这个FromBase64String(String)方法的意思呢,是跟Base64加密有关系的。
微软给出的解释是:
Converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array.
将指定的字符串(它将二进制数据编码为 Base64 数字)转换为等效的 8 位无符号整数数组。
翻译成人话为:
把那个“将二进制数据加密为Base64格式数据的指定字符串”转换为“等效的 8 位无符号整数数组”
再翻译成人话:
把被加密成Base64格式字符串的数组还原。

怪不得微软官方给出的例子是这样的。

补充知识:
C# 里的byte对应C++里的unsigned char ,我知道一点点C,这样就一下子理解了。
但是用法上有区别,仅仅是取值范围是0-255

namespace EncodeandDecode
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
            Console.WriteLine("The byte array: ");
            Console.WriteLine("   {0}\n", BitConverter.ToString(bytes));
            // BitConverter.ToString(bytes)是转换为16进制字符串

            string s = Convert.ToBase64String(bytes);
            //s = bytes转换成的16进制字符串再进行Base64加密而生成的字符串
            Console.WriteLine("The base 64 string: ");
            Console.WriteLine("   {0}\n", s);

            byte[] newBytes = Convert.FromBase64String(s);
            //把s还原回16进制字符串
            Console.WriteLine("The restored byte array: ");
            Console.WriteLine("   {0}\n", BitConverter.ToString(newBytes));
        }
    }
}

运行结果为:
The byte array:
02-04-06-08-0A-0C-0E-10-12-14

The base 64 string:
AgQGCAoMDhASFA==

The restored byte array:
02-04-06-08-0A-0C-0E-10-12-14

如果不想加密,就是把byte数组与字符串来回转换怎么搞呢?

namespace StringTurnToByte
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "1234";
            byte[] newBytes1 = Convert.FromBase64String(a);
            //将指定的字符串(它将二进制数据编码为 Base64 数字)转换为等效的 8 位无符号整数数组。
            string str1 = System.Text.Encoding.Default.GetString(newBytes1);
            Console.WriteLine(str1);

            byte[] newBytes2 = System.Text.Encoding.Default.GetBytes(a);
            //将指定字符串中的所有字符编码为一个字节序列,string转化为byte数组
            string str2 = System.Text.Encoding.Default.GetString(newBytes2);
            //转换byte为string
            Console.WriteLine(str2);
        }
    }
}

输出结果:
譵?
1234
第一行相当于对1234进行解密,自然出现乱码
第二行1234是对1234字符串转换为 byte数组,然后以字符串的形式输出byte数组

终了

posted @ 2019-08-23 10:44  卯毛  阅读(764)  评论(0编辑  收藏  举报