sair
sair

Reputation: 832

How to create a Byte Array Constant in C#?

I need to use AES algorithm in my project so i thought of having a constant Key for all the data to encrypt.how to create a global constant byte array in C# which is available as key ?

Upvotes: 4

Views: 6779

Answers (2)

John Alexiou
John Alexiou

Reputation: 29244

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

    }
}

Upvotes: 5

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

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.

Upvotes: 5

Related Questions