4

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 ?

8
  • 3
    You cannot. C# only allows const on string and numerical types. msdn.microsoft.com/en-us/library/e6w8fe1b.aspx You should use static readonly instead. Commented Mar 19, 2015 at 1:14
  • @Aron you can have const on reference type, but you wan't be able to assign anything but null to it. Commented Mar 19, 2015 at 1:15
  • 1
    The idea of a hard coded constant key is concerning for encryption purposes. It'd be better to derive the key from user input - like a password - using PBKDF2 or similar. Commented Mar 19, 2015 at 1:17
  • What exactly are you having difficulty with? Writing a C# program? Creating a byte array? What do you mean by “constant Key”? You mean declaring it const or you want to pass it to another method and ensure that method doesn't change it? Commented Mar 19, 2015 at 1:17
  • 1
    beware of decompile on your program, your key will be expose by anyone Commented Mar 19, 2015 at 1:19

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.