使用 PowerShell 对文件进行 AES 加密

2024-03-05

我能够使用此脚本成功对文件进行 AES 加密here https://gallery.technet.microsoft.com/EncryptDecrypt-files-use-65e7ae5d/file/165403/14/,使用 Windows 10、PowerShell 版本 5.1。

当我尝试在 Windows 7、PowerShell v2.0 上运行它时,出现错误:



New-CryptographyKey : You cannot call a method on a null-valued expression.
At C:\Users\IEUser\Desktop\enc.ps1:399 char:27
+ $key = New-CryptographyKey <<<<  -AsPlainText
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,New-CryptographyKey

Protect-File : Cannot bind argument to parameter 'KeyAsPlainText' because
it is an empty string.
At C:\Users\IEUser\Desktop\enc.ps1:401 char:77
+ Protect-File -FileName "$env:userprofile/Desktop/secret.txt" -KeyAsPlainText <<<<  $key
    + CategoryInfo          : InvalidData: (:) [Protect-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Protect-File
  

我该如何让它发挥作用?或者是否有另一种使用 Powershell 进行 AES 文件加密的交叉兼容解决方案?

EDIT:

我可能已经找到了 openSSL 的解决方案,但我仍然尝试了 @Mike Twc 的解决方案,得到了以下输出:

PS C:\Users\IEUser\Desktop> .\bouncy.ps1

TEST:

message: Some secret message
key: 9JODwRWWHp6+uACUiydFXNXPmWDHbcObhgqR/cvZ9zg=
IV (base64): U29tZV9QYXNzd29yZA==
IV (utf8): Some_Password
message bytes: 83 111 109 101 32 115 101 99 114 101 116 32 109 101 115 115 97 10
3 101
encrypted message bytes: 178 172 14 98 228 38 129 136 217 25 129 96 46 177 75 62
 50 5 190 46 51 108 81 38 90 74 197 166 44 96 120 252
encrypted message: sqwOYuQmgYjZGYFgLrFLPjIFvi4zbFEmWkrFpixgePw=
decrypted bytes: 83 111 109 101 32 115 101 99 114 101 116 32 109 101 115 115 97
103 101 0 0 0 0 0 0 0 0 0 0 0 0 0
decrypted message: Some secret message

您可以尝试使用 BouncyCastle 库。下面是使用该库的 AES 加密/解密实现。它在版本 2 模式下对我有效。

从这里下载最新编译的程序集(BouncyCastle.Crypto.dll):https://www.bouncycastle.org/csharp/index.html https://www.bouncycastle.org/csharp/index.html

将该 dll 提取到任何文件夹(例如 C:\temp),右键单击它,然后选中“取消阻止”

运行这段代码:

Add-Type -path "C:\stack\BouncyCastle.Crypto.dll"

$secRandom =  new-object Org.BouncyCastle.Security.SecureRandom

$message = "Some secret message"
$messageBytes = [System.Text.Encoding]::UTF8.GetBytes($message)

# if using files do this: 
# $messageBytes = [System.IO.File]::ReadAllBytes("C:\stack\out.txt")

#==== Key generation =====#

$keyBytes = New-Object byte[] 32
$secRandom.NextBytes($keyBytes) 
#$generator = [Org.BouncyCastle.Security.GeneratorUtilities]::GetKeyGenerator("AES")
$generator = New-Object Org.BouncyCastle.Crypto.CipherKeyGenerator 
$keyGenParam = new-object Org.BouncyCastle.Crypto.KeyGenerationParameters $keyBytes, 256
$generator.Init($keyGenParam)
$key = $generator.GenerateKey()
#or retreive from base64 string:
$key = [System.Convert]::FromBase64String("9JODwRWWHp6+uACUiydFXNXPmWDHbcObhgqR/cvZ9zg=")


#==== initialization vector (optional) =====#
#IV is a byte array, should be same as AES block size. By default 128 bit or 16 bytes (or less)

$IV = New-Object byte[] 16  
# below are some random IVs to play around, if IV parameter is not provided by user just keep it is array of 0s
$secRandom.NextBytes($IV) | Out-Null  #random generated 16 bytes
$IV = [System.Text.Encoding]::UTF8.GetBytes("Some_Password") #or use some random phrase


#==== Cipher set up =====#
#specify cipher type (typically CFB or CBC) and padding (use NOPADDING to skip). Check all possible values: 
#https://github.com/neoeinstein/bouncycastle/blob/master/crypto/src/security/CipherUtilities.cs

$cipher = [Org.BouncyCastle.Security.CipherUtilities]::GetCipher("AES/CFB/PKCS7")
$aesKeyParam = [Org.BouncyCastle.Security.ParameterUtilities]::CreateKeyParameter("AES", $key)
$keyAndIVparam = New-Object Org.BouncyCastle.Crypto.Parameters.ParametersWithIV $aesKeyParam, $IV


#==== Encrypt  =====#
#$cipher.Init($true,$aesKeyParam) 
$cipher.Init($true,$keyAndIVparam)
$dataSize = $cipher.GetOutputSize($messageBytes.Length)
$encMessageBytes = New-Object byte[]  $dataSize
$len = $cipher.ProcessBytes($messageBytes , 0, $messageBytes.Length, $encMessageBytes, 0)
$cipher.DoFinal($encMessageBytes, $len) | Out-Null

$encMessage = [System.Convert]::ToBase64String($encMessageBytes)

#if using files
#[System.IO.File]::WriteAllText("C:\stack\out.txt.aes", $encMessage)
#$encMessageBytes = [System.Convert]::FromBase64String([System.IO.File]::ReadAllText("C:\stack\out.txt.aes"))

#==== Decrypt =====#
#$cipher.Init($false,$aesKeyParam)
$cipher.Init($false,$keyAndIVparam)
$dataSize = $cipher.GetOutputSize($encMessageBytes.Length)
$decMessageBytes = New-Object byte[]  $dataSize
$len = $cipher.ProcessBytes($encMessageBytes , 0, $encMessageBytes.Length, $decMessageBytes, 0)
$cipher.DoFinal($decMessageBytes, $len) | Out-Null

$decMessage = [System.Text.Encoding]::UTF8.GetString($decMessageBytes).Trim([char]0)

#==== TEST =====#
Write-Host "`nTEST:`n"
Write-Host "message: $message"
Write-Host "key: $([System.Convert]::ToBase64String($key))"
Write-Host "IV (base64): $([System.Convert]::ToBase64String($IV))"
Write-Host "IV (utf8): $([System.Text.Encoding]::UTF8.GetString($IV))"
Write-Host "message bytes: $messageBytes"
Write-Host "encrypted message bytes: $encMessageBytes"
Write-Host "encrypted message: $encMessage"
Write-Host "decrypted bytes: $decMessageBytes"
Write-Host "decrypted message: $decMessage"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 PowerShell 对文件进行 AES 加密 的相关文章

随机推荐