|
55 | 55 | ValueFromPipelineByPropertyName |
56 | 56 | )] |
57 | 57 | [Alias('CipherText')] |
| 58 | + [ValidateNotNullOrEmpty()] |
58 | 59 | [string] $SealedBox, |
59 | 60 |
|
60 | 61 | # The base64-encoded public key used for decryption. |
|
63 | 64 |
|
64 | 65 | # The base64-encoded private key used for decryption. |
65 | 66 | [Parameter(Mandatory)] |
| 67 | + [ValidateNotNullOrEmpty()] |
66 | 68 | [string] $PrivateKey |
67 | 69 | ) |
68 | 70 |
|
69 | 71 | begin { |
70 | | - if (-not $script:Supported) { throw 'Sodium is not supported on this platform.' } |
71 | | - $null = [PSModule.Sodium]::sodium_init() |
| 72 | + Initialize-Sodium |
72 | 73 | } |
73 | 74 |
|
74 | 75 | process { |
75 | | - $ciphertext = [System.Convert]::FromBase64String($SealedBox) |
76 | | - |
77 | | - $privateKeyByteArray = [System.Convert]::FromBase64String($PrivateKey) |
78 | | - if ($privateKeyByteArray.Length -ne 32) { throw 'Invalid private key.' } |
79 | | - |
80 | | - if ([string]::IsNullOrWhiteSpace($PublicKey)) { |
81 | | - $publicKeyByteArray = Get-SodiumPublicKey -PrivateKey $PrivateKey -AsByteArray |
82 | | - } else { |
83 | | - $publicKeyByteArray = [System.Convert]::FromBase64String($PublicKey) |
84 | | - if ($publicKeyByteArray.Length -ne 32) { throw 'Invalid public key.' } |
| 76 | + try { |
| 77 | + if (-not [string]::IsNullOrWhiteSpace($PublicKey)) { |
| 78 | + return [PSModule.Sodium]::OpenSealBase64($SealedBox, $PrivateKey, $PublicKey) |
| 79 | + } |
| 80 | + return [PSModule.Sodium]::OpenSealBase64($SealedBox, $PrivateKey) |
| 81 | + } catch [System.Management.Automation.MethodInvocationException] { |
| 82 | + throw $_.Exception.InnerException |
85 | 83 | } |
86 | | - |
87 | | - $overhead = [PSModule.Sodium]::crypto_box_sealbytes().ToUInt32() |
88 | | - $decryptedBytes = New-Object byte[] ($ciphertext.Length - $overhead) |
89 | | - |
90 | | - $result = [PSModule.Sodium]::crypto_box_seal_open( |
91 | | - $decryptedBytes, $ciphertext, [UInt64]$ciphertext.Length, $publicKeyByteArray, $privateKeyByteArray |
92 | | - ) |
93 | | - |
94 | | - if ($result -ne 0) { |
95 | | - throw 'Decryption failed.' |
96 | | - } |
97 | | - |
98 | | - return [System.Text.Encoding]::UTF8.GetString($decryptedBytes) |
99 | 84 | } |
100 | 85 | } |
0 commit comments