Skip to main content

Create a AES crypto key in PowerShell. Includes encrypt and decrypt functions.

# Original: https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Create-AesKey.ps1
# Original: https://gist.github.com/ctigeek/2a56648b923d198a6e60
# Found in article: https://www.sabin.io/blog/adding-an-azure-active-directory-application-and-key-using-powershell/

function Create-AesManagedObject($key, $IV)
{
    $aesManaged = New-Object "System.Security.Cryptography.AesManaged"
    $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
    $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
    $aesManaged.BlockSize = 128
    $aesManaged.KeySize = 256

    if ($IV)
    {
        if ($IV.getType().Name -eq "String")
        {
            $aesManaged.IV = [System.Convert]::FromBase64String($IV)
        }
        else
        {
            $aesManaged.IV = $IV
        }
    }
    # else
    # {
    #     $aesManaged.GenerateIV()
    #     $randomIv = [System.Convert]::ToBase64String($aesManaged.IV);
    #     Write-Host "Generated a random IV: $randomIv"
    # }

    if ($key)
    {
        if ($key.getType().Name -eq "String")
        {
            $aesManaged.Key = [System.Convert]::FromBase64String($key)
        }
        else
        {
            $aesManaged.Key = $key
        }
    }

    return $aesManaged
}

function Create-AesKey()
{
    $aesManaged = Create-AesManagedObject
    $aesManaged.GenerateKey()

    return [System.Convert]::ToBase64String($aesManaged.Key)
}

function Encrypt-String($key, $unencryptedString)
{
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($unencryptedString)

    $aesManaged = Create-AesManagedObject $key
    $encryptor = $aesManaged.CreateEncryptor()
    $encryptedData = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length);
    [byte[]] $fullData = $aesManaged.IV + $encryptedData

    $aesManaged.Dispose()

    return [System.Convert]::ToBase64String($fullData)
}

function Decrypt-String($key, $encryptedStringWithIV)
{
    $bytes = [System.Convert]::FromBase64String($encryptedStringWithIV)
    $IV = $bytes[0..15]

    $aesManaged = Create-AesManagedObject $key $IV
    $decryptor = $aesManaged.CreateDecryptor();
    $unencryptedData = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16);

    $aesManaged.Dispose()

    return [System.Text.Encoding]::UTF8.GetString($unencryptedData).Trim([char]0)
}

# $key = Create-AesKey
# Write-Host $key
# $unencryptedString = "blahblahblah"
# $encryptedString = Encrypt-String $key $unencryptedString
# $backToPlainText = Decrypt-String $key $encryptedString