# 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 ```ps1 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 ```ps1 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](https://www.linqpad.net/) or by copying the following code into a new project and referencing `System.Security`. #### Base64 ```cs using (var rijndael = System.Security.Cryptography.Rijndael.Create()) { rijndael.GenerateKey(); var key = Convert.ToBase64String(rijndael.Key); Console.WriteLine(key); } ``` #### Hex ```cs 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](https://www.openssl.org/) 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: ```shell openssl rand -base64 32 ``` #### Plaintext Generates 32 random characters (256bits): ```shell openssl rand 32 ``` > [!NOTE] > Be aware that strings parsed by NServiceBus do not use extended ASCII which limits the key range to 7 bits per character.