C# 从字节数组转换为 base64 并返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11634237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion from byte array to base64 and back
提问by crawfish
I am trying to:
我在尝试着:
- Generate a byte array.
- Convert that byte array to base64
- Convert that base64 string back to a byte array.
- 生成字节数组。
- 将该字节数组转换为 base64
- 将该 base64 字符串转换回字节数组。
I've tried out a few solutions, for example those in this question.
我已经尝试了一些解决方案,例如在这个问题中的那些。
For some reason the initial and final byte arrays do not match. Here is the code used:
由于某种原因,初始和最终字节数组不匹配。这是使用的代码:
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] originalArray = new byte[32];
rng.GetBytes(key);
string temp_inBase64 = Convert.ToBase64String(originalArray);
byte[] temp_backToBytes = Encoding.UTF8.GetBytes(temp_inBase64);
}
My questions are:
我的问题是:
Why do "originalArray" and "temp_backToBytes" not match? (originalArray has length of 32, temp_backToBytes has a length of 44, but their values are also different)
Is it possible to convert back and forth, and if so, how do I accomplish this?
为什么“originalArray”和“temp_backToBytes”不匹配?(originalArray 的长度为 32,temp_backToBytes 的长度为 44,但它们的值也不同)
是否可以来回转换,如果可以,我该如何实现?
采纳答案by dasblinkenlight
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
编码数组长约四分之一的原因是 base-64 编码仅使用每个字节中的 6 位;这就是它存在的原因 - 以适合通过纯 ASCII 通道(例如电子邮件)交换的方式对任意数据(可能带有零和其他不可打印字符)进行编码。
The way you get your original array back is by using Convert.FromBase64String:
取回原始数组的方法是使用Convert.FromBase64String:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

