Functions/ConvertTo-FIPSSecureString.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<#
.SYNOPSIS Converts a string of encrypted text back into a SecureString object with a FIPS compliant algorithm using a pre-shared key. The Pre-Shared key can be provided as either a 32 byte array or a SecureString value. .PARAMETER EncryptedString The string of encrypted text to convert back into a SecureString object .PARAMETER Key An array of 32 bytes that will be used as a the pre-shared key for decryption. .PARAMETER SecureKey A SecureString that will be converted into a 32 byte array used as the pre-shared key for decryption. .EXAMPLE $EncryptedText = Get-Content ./encryptedText.txt $MySecret = ConvertTo-FIPSSecureString -EncryptedString $EncryptedText -SecureKey ( ConvertTo-SecureString -String 'Pr3$haredK3y' -AsPlainText -Force ) #> function ConvertTo-FIPSSecureString { [CmdletBinding()] param ( [Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$true,ParameterSetName='KeyByte')] [Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$true,ParameterSetName='SecureKey')] [ValidateNotNullOrEmpty()] [System.String] $EncryptedString, [Parameter(Mandatory=$True,ParameterSetName='KeyByte')] [ValidateNotNullOrEmpty()] [System.Byte[]] $Key, [Parameter(Mandatory=$True,ParameterSetName='SecureKey')] [ValidateNotNullOrEmpty()] [System.Security.SecureString] $SecureKey ) if ($PSBoundParameters.ContainsKey('SecureKey')) { $key = Convert-SecureStringTo32ByteKey -SecureString $SecureKey } if ($null -eq $key -or $key.GetLength(0) -ne 32) { throw 'Key must be provided as a 32byte (256bit) byte array' } $dataBytes = [System.Convert]::FromBase64String($EncryptedString) $iv = $dataBytes[0..15] $aes = New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider $aes.Mode = [System.Security.Cryptography.CipherMode]::CBC $aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $aes.BlockSize = 128 $aes.KeySize = 256 $aes.Key = $Key $aes.IV = $iv $decryptionObject = $aes.CreateDecryptor() Write-Verbose -Message 'Converting AES encrypted string to SecureString' [System.Byte[]] $decryptedDataBytes =$decryptionObject.TransformFinalBlock($dataBytes,16,$dataBytes.Length -16) $aes.Dispose() return ( [System.Text.Encoding]::UTF8.GetString($decryptedDataBytes) | ConvertTo-SecureString -AsPlainText -Force ) } |