java_geek
java_geek

Reputation: 18045

AES encryption key generation using AesCng

I am using AesCng to generate an encryption key using the code below:

using System;
using System.Security.Cryptography;
using System.Text;

namespace EncryptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Encoding.UTF8.GetString(GenerateKey()));
        }

        static byte[] GenerateKey()
        {
            using (AesCng cng = new AesCng())
            {
                cng.GenerateKey();
                return cng.Key;
            }
        }
    }
}

When I check the key in the console, its shown as r?▬?^?-?▲?ZQ^???♥$)??8w?f▬?[??

It looks like some characters are not getting resolved. Can someone help me understand what I am doing wrong?

Upvotes: 1

Views: 490

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129827

An AES key is just a series of bytes. These bytes are not guaranteed to be printable characters, either in UTF8, ASCII or any other character encoding. This is normal, and there's nothing wrong with the generated key.

Generally if you want to turn a series of arbitrary bytes into a printable string, you would use Base-64 encoding on it, like this:

Console.WriteLine(Convert.ToBase64String(GenerateKey()));

This will give you an output something like this:

VX/oYK1P5LQAH5MqiRHyNDtZyNcQGEUpIRpnpsY+buk=

Fiddle: https://dotnetfiddle.net/5bDi0c

See Convert.ToBase64String(byte[]) and Convert.FromBase64String(string) for more info and examples.

Upvotes: 3

Related Questions