-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathConvertFrom-FipsSecureString.ps1
More file actions
71 lines (56 loc) · 2.63 KB
/
ConvertFrom-FipsSecureString.ps1
File metadata and controls
71 lines (56 loc) · 2.63 KB
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 SecureString object into encrypted text 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 SecureString
The SecureString object that will returned as an encrypted string.
.PARAMETER Key
An array of 32 bytes that will be used as a the pre-shared key for encryption.
.PARAMETER SecureKey
A SecureString that will be converted into a 32 byte array used as the pre-shared key for encryption.
.EXAMPLE
ConvertFrom-FIPSSecureString -SecureString $MySecretValue -SecureKey ( ConvertTo-SecureString -String 'Pr3$haredK3y' -AsPlainText -Force ) | Out-File ./encryptedText.txt
Encrypts a SecureString object and saves it to disk.
#>
function ConvertFrom-FIPSSecureString
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$true,ParameterSetName="KeyByte")]
[Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$true,ParameterSetName="SecureKey")]
[ValidateNotNullOrEmpty()]
[System.Security.SecureString]
$SecureString,
[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'
}
$btsr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
$dataBytes = [System.Text.Encoding]::UTF8.GetBytes([Runtime.InteropServices.Marshal]::PtrToStringAuto($btsr))
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($btsr)
$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
$encryptionObject = $aes.CreateEncryptor()
Write-Verbose -Message 'Converting SecureString to encrypted string with AESCryptoServiceProvider'
[System.Byte[]]$encryptedDataBytes = $aes.IV + ($encryptionObject.TransformFinalBlock($dataBytes,0,$dataBytes.Length))
$aes.Dispose()
return [System.Convert]::ToBase64String($encryptedDataBytes)
}