从字节数组转换为 base64 并返回
我正在尝试:
- 生成一个字节数组.
- 将该字节数组转换为 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);
}
我的问题是:
为什么originalArray"和temp_backToBytes"不匹配?(originalArray 的长度为 32,temp_backToBytes 的长度为 44,但它们的值也不同)
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?
编码数组长约四分之一的原因是 base-64 编码仅使用每个字节中的 6 位;这就是它存在的原因 - 以适合通过纯 ASCII 通道(例如电子邮件)交换的方式对任意数据(可能带有零和其他不可打印字符)进行编码.
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.
获取原始数组的方法是使用 Convert.FromBase64String
:
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);