简体   繁体   中英

How to create a Byte Array Constant in C#?

我需要在我的项目中使用 AES 算法,所以我想为所有要加密的数据设置一个常量密钥。如何在 C# 中创建一个全局常量字节数组,它可以作为密钥使用?

The only byte[] constant you can create is following one:

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).

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

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.

class Program
{
    const string key = "6Z8FgpPBeXg=";
    static void Main(string[] args)
    {
        var buffer = Convert.FromBase64String(key);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM