Generate random bytes for TripleDES key C#
Asked Answered
C

5

8

I need to generate byte array for TripleDES encryption. I don't want to use .generateKey() because I need to know the bytes in the key to pass them to another application.

Thanks for the replies but I forgot to mention one thing: the bytes have to be odd parity. Otherwise I can't generate a TripleDES key from them. I'm not so familiar with the odd parity, so I guess have to create a byte check if it has odd parity or not; then if it does put it in the array, otherwise not.

Comptometer answered 18/3, 2011 at 7:48 Comment(0)
B
4

If you need to ensure the odd parity, you have to compute it 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;
Bra answered 18/3, 2011 at 8:36 Comment(0)
H
3

How 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 crypto work (in terms of reasonably secure, hard-to-predict random data), whereas System.Random isn't.

Harborage answered 18/3, 2011 at 7:51 Comment(1)
RandomNumberGenerator rng = new RandomNumberGenerator.Create();Gennie
L
2

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

TripleDES provider = TripleDES.Create();

byte[] key = provider.Key;

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

Note that the other answers lack a TripleDES.IsWeakKey.

Lonnalonnard answered 16/11, 2011 at 22:58 Comment(0)
P
1

The GetBytes method returns crypthographically 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);
        }
Pliske answered 18/3, 2011 at 7:53 Comment(1)
Thnx, thats working but look at my edited question. I forgot to say about the odd parity.Comptometer
T
-1

What about Random.NextBytes()

More info here.

Tomato answered 18/3, 2011 at 7:51 Comment(1)
Random isn't secure for cryptographic use.Marmawke

© 2022 - 2024 — McMap. All rights reserved.