Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Byte Array Constant in C#?

Tags:

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 ?

like image 705
pola sai ram Avatar asked Nov 04 '25 12:11

pola sai ram


2 Answers

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 image 147
MarcinJuraszek Avatar answered Nov 07 '25 10:11

MarcinJuraszek


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

    }
}
like image 43
John Alexiou Avatar answered Nov 07 '25 09:11

John Alexiou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!