Skip to content

Commit ebd97ef

Browse files
committed
#2 | Disposing of the AesGcm instance unconditionally
fixes #2
1 parent 017c3f4 commit ebd97ef

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

Crypto.AES/Public/Protect-Data.ps1

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
function Protect-Data {
22
[CmdletBinding()]
33
param (
4-
[Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Key" )]
4+
[Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Key")]
55
[byte[]]$Key,
6-
[Parameter(Mandatory = $true, Position = 0, ParameterSetName = "GCM" )]
6+
7+
[Parameter(Mandatory = $true, Position = 0, ParameterSetName = "GCM")]
78
[System.Security.Cryptography.AesGcm]$GCM,
8-
[Parameter(Mandatory = $true, Position = 1 )]
9+
10+
[Parameter(Mandatory = $true, Position = 1)]
911
[byte[]]$Data,
10-
[Parameter(Mandatory = $false, Position = 2 )]
12+
13+
[Parameter(Mandatory = $false, Position = 2)]
1114
[byte[]]$Nonce,
12-
[Parameter(Mandatory = $false, Position = 3 )]
15+
16+
[Parameter(Mandatory = $false, Position = 3)]
1317
[Switch]$Combined
1418
)
1519

@@ -27,17 +31,23 @@ function Protect-Data {
2731
$tag = [byte[]]::new(16)
2832

2933
if ($PSCmdlet.ParameterSetName -eq 'Key') {
30-
$gcm = [System.Security.Cryptography.AesGcm]::new($Key)
34+
$GCM = [System.Security.Cryptography.AesGcm]::new($Key)
35+
try {
36+
$GCM.Encrypt($Nonce, $Data, $cipherOutput, $tag)
37+
}
38+
finally {
39+
$GCM.Dispose()
40+
}
41+
}
42+
else {
43+
$GCM.Encrypt($Nonce, $Data, $cipherOutput, $tag)
3144
}
32-
33-
$gcm.Encrypt($Nonce, $Data, $cipherOutput, $tag)
34-
$gcm.Dispose()
3545

3646
if ($Combined) {
3747
$output = [byte[]]::new($cipherOutput.Length + $Nonce.Length + $tag.Length)
38-
[System.Buffer]::BlockCopy($tag, 0, $output, 0, $tag.Length);
39-
[System.Buffer]::BlockCopy($cipherOutput, 0, $output, $tag.Length, $cipherOutput.Length);
40-
[System.Buffer]::BlockCopy($Nonce, 0, $output, $tag.Length + $cipherOutput.Length, $Nonce.Length);
48+
[System.Buffer]::BlockCopy($tag, 0, $output, 0, $tag.Length)
49+
[System.Buffer]::BlockCopy($cipherOutput, 0, $output, $tag.Length, $cipherOutput.Length)
50+
[System.Buffer]::BlockCopy($Nonce, 0, $output, $tag.Length + $cipherOutput.Length, $Nonce.Length)
4151
Write-Output $output -NoEnumerate
4252
}
4353
else {

0 commit comments

Comments
 (0)