1

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?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
java_geek
  • 17,585
  • 30
  • 91
  • 113
  • 1
    You have a `byte[]` and seems you're wanting to print the string representation. I think you would want to use `Convert.ToBase64String(GenerateKey())` – jimnkey Apr 11 '21 at 05:37

1 Answers1

3

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.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300