Search code examples
c#aes

Write out AES key and IV in C#


Im trying to have c# generate a AES key and IV. But I am unable to find a way to have it write out the Key and IV.

static void Main(string[] args)
    {
        using (var aes = Aes.Create())
        {
            aes.KeySize = 256;
            aes.BlockSize = 128;
            aes.Padding = PaddingMode.Zeros;
            aes.Mode = CipherMode.CBC;
            var iv = aes.GenerateIV();
            aes.GenerateKey();
            

        }

    }

When I assign a var to the generate method it gives an error of cannot assign void to an implicitly-type variable. When i can it to a byte array it displays cannot implicitly convert type void to byte.


Solution

  • You need to access Key and IV properties of Aes class to get values of Key and IV.

    Aes Object when created by doing Aes.Create, will have IV and Key values available from it. You just need to retrieve them via Key and IV properties.

    Key and IV properties are of type byte[] so you need to convert them to string to be able to see in text format.

    Consider following code.

    using (var aes = Aes.Create())
    {
        aes.KeySize = 256;
        aes.BlockSize = 128;
        aes.Padding = PaddingMode.Zeros;
        aes.Mode = CipherMode.CBC;
        
        var key = Convert.ToBase64String(aes.Key);
        var iv = Convert.ToBase64String(aes.IV);
         
        Console.WriteLine(key); 
        Console.WriteLine(iv);
    }