Skip to content

Commit 1bccf8a

Browse files
committed
#1 The nonce isn’t being initialized properly - tests & refactoring
1 parent 16c0bea commit 1bccf8a

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function Get-RandomNonce {
2+
[CmdletBinding()]
3+
param (
4+
[Parameter(Mandatory = $true)]
5+
[ValidateRange(1, [int]::MaxValue)]
6+
[int]$Length
7+
)
8+
9+
begin {
10+
Write-Verbose "Cmdlet Get-RandomNonce - Begin"
11+
}
12+
13+
process {
14+
Write-Verbose "Cmdlet Get-RandomNonce - Generating a nonce of length $Length"
15+
16+
$nonce = [byte[]]::new($Length)
17+
[System.Security.Cryptography.RandomNumberGenerator]::Fill($nonce)
18+
Write-Output $nonce -NoEnumerate
19+
}
20+
21+
end {
22+
Write-Verbose "Cmdlet Get-RandomNonce - End"
23+
}
24+
}

Crypto.AES/Public/Protect-Data.ps1

+1-2
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@ function Protect-Data {
2424
process {
2525
Write-Verbose "Cmdlet Protect-Data - Process"
2626
if (!$Nonce) {
27-
$Nonce = [byte[]]::new(12)
28-
[System.Security.Cryptography.RandomNumberGenerator]::Fill($Nonce)
27+
$Nonce = Get-RandomNonce -Length 12
2928
}
3029
$cipherOutput = [byte[]]::new($Data.Length)
3130
$tag = [byte[]]::new(16)

Tests/Crypto.AES.Tests.ps1

+5-1
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,14 @@ Describe 'Crypto.AES.Tests' {
5858
}
5959

6060
Context "Protect-Data - signature" {
61-
$Key = [byte[]]::new(32)
61+
$Key = [byte[]]::new(32)
6262
$nonce = [byte[]]::new(12)
63+
$nonce[0] = 104 # random value to test with mock
6364
$data = $encoding.GetBytes("Test")
6465

66+
Mock -CommandName Get-RandomNonce -ModuleName Crypto.AES -MockWith {
67+
Write-Output $nonce -NoEnumerate
68+
}
6569

6670
It "optional nonce" {
6771
$r_explicit = Protect-Data -Key $Key -Data $data -Nonce $nonce

0 commit comments

Comments
 (0)