Generate random bytes for C # TripleDES key

I need to create an array of bytes for TripleDES encryption. I do not want to use .generateKey() , because I need to know the bytes in the key to transfer them to another application.

Thanks for the answers, but I forgot to mention one thing: bytes should be odd. Otherwise, I cannot generate the TripleDES key for them. I am not very good at odd parity, so, in my opinion, you need to create a byte check if it has odd parity or not; then if it puts it in an array, otherwise not.

+8
c # tripledes
source share
5 answers

If you need to provide odd parity, you must figure it out yourself. This should do:

 var rng = new RNGCryptoServiceProvider(); var key = new byte[24]; rng.GetBytes(key); for(var i = 0; i < key.Length; ++i) { int keyByte = key[i] & 0xFE; var parity = 0; for (var b = keyByte; b != 0; b >>= 1) parity ^= b & 1; key[i] = (byte)(keyByte | (parity == 0 ? 1 : 0)); } return key; 
+4
source share

What about:

 RandomNumberGenerator rng = RandomNumberGenerator.Create(); byte[] key = new byte[24]; // For a 192-bit key rng.GetBytes(key); tripleDes.Key = key; 

Note that RandomNumberGenerator is suitable for cryptographic work (in terms of reasonably reliable, hard-to-predict random data), while System.Random not.

+3
source share

But ... what's the problem with just:

 TripleDES provider = TripleDES.Create(); byte[] key = provider.Key; 

There you will get your key used by en- and decryptor created with this instance.

Note that the other answers are missing TripleDES.IsWeakKey .

+2
source share

The GetBytes method returns a cryptographically strong sequence of values:

  var rng = System.Security.Cryptography.RandomNumberGenerator.Create(); byte [] barr = new byte[128]; rng.GetBytes(barr); foreach (var b in barr) { Console.WriteLine(b); } 
+1
source share

How about Random.NextBytes()

More details here .

-one
source share

All Articles