Generating secure random strong encryption keys

There are multiple ways of generating an encryption key. Most implementations rely on a random object. All examples mentioned here use a secure cryptographic randomizer.

PowerShell

Base64

Add-Type -AssemblyName System.Security

[Reflection.Assembly]::LoadWithPartialName("System.Security")
$rijndael = new-Object System.Security.Cryptography.RijndaelManaged
$rijndael.GenerateKey()
Write-Host([Convert]::ToBase64String($rijndael.Key))
$rijndael.Dispose()

Hex

Add-Type -AssemblyName System.Security

[Reflection.Assembly]::LoadWithPartialName("System.Security")
$rijndael = new-Object System.Security.Cryptography.RijndaelManaged
$rijndael.GenerateKey()
Write-Host([System.BitConverter]::ToString($rijndael.Key).Replace("-", "").ToLowerInvariant())
$rijndael.Dispose()

C#

The code snippets below can be run from LINQPad or by copying the following code into a new project and referencing System.Security.

Base64

using (var rijndael = System.Security.Cryptography.Rijndael.Create())
{
    rijndael.GenerateKey();
    var key = Convert.ToBase64String(rijndael.Key);
    Console.WriteLine(key);
}

Hex

using (var rijndael = System.Security.Cryptography.Rijndael.Create())
{
    rijndael.GenerateKey();
    var key = BitConverter.ToString(rijndael.Key)
        .Replace("-", string.Empty)
        .ToLowerInvariant();
    Console.WriteLine(key);
}

OpenSSL

OpenSSL is well known for its ability to generate certificates but it can also be used to generate random data.

Base64

Generates 32 random bytes (256bits) in a base64 encoded output:

openssl rand -base64 32

Plaintext

Generates 32 random characters (256bits):

openssl rand 32
Be aware that strings parsed by NServiceBus do not use extended ASCII which limits the key range to 7 bits per character.

Related Articles


Last modified