[英]How to create a Byte Array Constant in C#?
我需要在我的项目中使用 AES 算法,所以我想为所有要加密的数据设置一个常量密钥。如何在 C# 中创建一个全局常量字节数组,它可以作为密钥使用?
The only byte[]
constant you can create is following one:您可以创建的唯一byte[]
常量如下:
const byte[] myBytes = null;
That's because byte[]
(or every array in general) is a reference type, and reference type constants can only have null
value assigned to it (with the exception of string
type, which can be used with string literals).那是因为byte[]
(或一般的每个数组)都是引用类型,并且引用类型常量只能分配null
值( string
类型除外,它可以与字符串文字一起使用)。
Constants can be numbers, Boolean values, strings, or a null reference.常量可以是数字、布尔值、字符串或空引用。
Like this:像这样:
static readonly byte[] key = new byte[] { .. }
Or maybe consider using a string, and then converting it to bytes using Bin64
或者考虑使用字符串,然后使用Bin64
将其转换为字节
Note that the array is read/write and thus not constant.请注意,数组是读/写的,因此不是常量。
Edit编辑
A better way is to store a constant string in Bin64 and convert back to byte[]
on the fly.更好的方法是将一个常量字符串存储在 Bin64 中并动态转换回byte[]
。
class Program
{
const string key = "6Z8FgpPBeXg=";
static void Main(string[] args)
{
var buffer = Convert.FromBase64String(key);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.