Skip to content

Instantly share code, notes, and snippets.

@lennybacon
Last active August 7, 2024 10:35
Show Gist options
  • Save lennybacon/9fcce97f84d1b760e8da0e9d0738536a to your computer and use it in GitHub Desktop.
Save lennybacon/9fcce97f84d1b760e8da0e9d0738536a to your computer and use it in GitHub Desktop.
Generate a new AES 256 Key with PowerShell
$random = [System.Security.Cryptography.RandomNumberGenerator]::Create();
$buffer = New-Object byte[] 32;
$random.GetBytes($buffer);
[BitConverter]::ToString($buffer).Replace("-", [string]::Empty);
@gajjardarshithasmukhbhai

@lennybacon I added the some steps to run the above scripts for various OS:

Windows:

  • Open a PowerShell terminal (Command Prompt or PowerShell).
  • Copy and paste the script into the terminal.
  • Press Enter to run the script.

MacOS:

  • Open a terminal (you can find it in Applications > Utilities > Terminal).
  • Use the pwsh command (PowerShell Core) or powershell (if installed) to run the script. For example:
pwsh -File path/to/your/script.ps1

Linux:

  • Open a terminal.
  • Use the pwsh command (PowerShell Core) to run the script. For example:
pwsh -File path/to/your/script.ps1

@MONTANA241
Copy link

What should I do if I need several AES 256 keys at once? Thks!

@lennybacon
Copy link
Author

What should I do if I need several AES 256 keys at once? Thks!

Put it in a for-Loop?

$random = [System.Security.Cryptography.RandomNumberGenerator]::Create();

for($i=0; $i -lt 10; $i++){
  $buffer = New-Object byte[] 32;
  $random.GetBytes($buffer);
  $key = [BitConverter]::ToString($buffer).Replace("-", [string]::Empty);
   Write-Host "Key $($i): $($key)"
 }

@MONTANA241
Copy link

What should I do if I need several AES 256 keys at once? Thks!

Put it in a for-Loop?

$random = [System.Security.Cryptography.RandomNumberGenerator]::Create();

for($i=0; $i -lt 10; $i++){
  $buffer = New-Object byte[] 32;
  $random.GetBytes($buffer);
  $key = [BitConverter]::ToString($buffer).Replace("-", [string]::Empty);
   Write-Host "Key $($i): $($key)"
 }

Thanks a lot!!!

@LamonJ
Copy link

LamonJ commented Aug 6, 2024

Can you make a script that would add special characters in the key?

@lennybacon
Copy link
Author

Can you make a script that would add special characters in the key?

The output is the Hexadecimal representation of the key - by definition this is only 0-9 and a-f. Special characters are encoded in the same way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment