使用PowerShell对文件进行AES加密 [英] AES encryption on files using PowerShell

查看:243
本文介绍了使用PowerShell对文件进行AES加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用此脚本成功AES加密文件

I was able to AES encrypt files successfully using this script here, using Windows 10, PowerShell version 5.1.

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

When I tried running it on Windows 7, PowerShell v2.0, I get an error:


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文件加密的另一种相互兼容的解决方案?

How do I make it work? Or is there another cross-compatible solution for AES file encryption using Powershell?

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

I might've found a solution with openSSL, but I still tried @Mike Twc's solution, got this output:

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模式下对我有效.

You may try to use BouncyCastle library. Below is the AES encryption/decryption implementation with that library. It worked on my end in version 2 mode.

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

Download latest compiled assembly (BouncyCastle.Crypto.dll) from here: https://www.bouncycastle.org/csharp/index.html

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

Extract that dll to any folder (say C:\temp), right click on it, and check "Unblock"

运行以下代码:

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"

这篇关于使用PowerShell对文件进行AES加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆