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 ?
Asked
Active
Viewed 6,206 times
4
-
3You cannot. C# only allows `const` on `string` and `numerical` types. https://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx You should use `static readonly` instead. – Aron Mar 19 '15 at 01:14
-
@Aron you can have `const` on reference type, but you wan't be able to assign anything but `null` to it. – MarcinJuraszek Mar 19 '15 at 01:15
-
1The 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. – vcsjones Mar 19 '15 at 01: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? – Dour High Arch Mar 19 '15 at 01:17
-
1beware of decompile on your program, your key will be expose by anyone – Eric Mar 19 '15 at 01:19
-
This is probably exactly what you are looking for: http://stackoverflow.com/questions/4501289/c-sharp-byte-encryption – Gary Kaizer Mar 19 '15 at 01:26
-
Possible duplicate of [Declaring a long constant byte array](http://stackoverflow.com/questions/15560007/declaring-a-long-constant-byte-array) – Eagle-Eye May 18 '17 at 19:06
-
+1 because this is the number one result from google on this topic - although the detail question itself is stated very foggy :-) ... and one of the answers below is really useful (at least for me) – John Ranger Jan 18 '20 at 12:41
2 Answers
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.

MarcinJuraszek
- 124,003
- 15
- 196
- 263
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);
}
}

John Alexiou
- 28,472
- 11
- 77
- 133