ISSUE :
 
Profile photo
Submitted by Sam Buchana
on August 24th, 2012 at 07:58:12 EST

Create Triple DES key in C# .NET

How to create Triple DES key in C# .NET? I read that tripleDES key should include parity check.


Profile photo
Replied by RaKumar
on August 24th, 2012 at 08:45:19 EST
TripleDES key requires odd parity check. Here is sample code to generate TripleDES key,

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

Profile photo
Replied by SBajra
on August 24th, 2012 at 08:52:10 EST
One of the easiest way in .NET to generate TripleDES key is:

System.Security.Cryptography.TripleDES.Create().Key

This returns back byte[] with TripleDES key.

By the way, .NET really does not enforce parity check so you could use any GUID with 24 characters which will make it 192 bit key. I noticed, this is true even with Java implementation of TripleDES that it does not enforce parity check and any 24 characters key will work.

Profile photo
Replied by Sam Buchana
on August 24th, 2012 at 09:28:34 EST
Thanks RaKumar and SBajra.

After looking into both options. I think the solution provided by RaKumar is more robust and follow TripleDES specification and maintain ODD parity.

When I used .NET built-in TripleDES key generator:

System.Security.Cryptography.TripleDES.Create().Key

It is not generating ODD parity. Seems like Microsoft implementation does not care of ODD partiy in TripleDES key.

So, I chose to use manual algorithm provided by RaKumar.