Generating AES-256 bits encryption key in C# ??

kwnan
kwnan used Ask the Experts™
on
I want to generate AES encryption key to be sent to the the other party in order to communicate securely. In the beginning the two nodes will create a shared session key by using Deffie-Helman protocol, then one of them will genreate AES key and send it to the other node through the secure channel(i.e. DH protocol).

So Could you please help in generating AES-256 bits in C# without using it to encrypt any plaintext. I just want the key itself.

Regards
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
If I understand your question correctly, then I would think you could do something along the lines of:

System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();

crypto.KeySize = 256;
crypto.GenerateKey();
byte[] key = crypto.Key;

Open in new window

Author

Commented:
Thanks yes that what I need but I want to print the key itself and I have added the statment Console.WriteLine("My key is {0}", key); and did not work, it prints this: My key is System.Byte[]

Could you help in how to print the key.

Regards
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Since we are dealing with bytes, I'm not sure printing it to the screen is going to yield friendly, readable text. We're dealing with values from 0 - 255, and the first 32 values (i.e. 0 - 31) are the "non-printable" characters. As it sounds, you wouldn't see anything for those characters.

To print the numeric values themselves, you can loop through the array:

foreach (byte b in key)
{
    Console.WriteLine(b.ToString());
}

Open in new window


If you'd like to try and turn these into characters, then you can use the ASCII class to decode the values:

string strKey = System.Text.Encoding.ASCII.GetString(key);

Open in new window


...but as I mentioned, I don't think this will be reliable for your purposes.

Author

Commented:
Ok thank you very much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial