任何人都可以帮助我使用AWS KMS加密/解密文件夹中文件的内容。 我希望PowerShell脚本也这样做。 事情是我想在上传到亚马逊s3桶之前加密文件夹,并想从s3桶下载后解密它。
P.S:我是PowerShell脚本新手。
提前致谢!
答案 0 :(得分:0)
你可以从史蒂文找到一本好的教程here。
我只是复制粘贴他的代码,这对我来说非常合适。
加密:
function Invoke-KMSEncryptText
(
[Parameter(Mandatory=$true,Position=1,HelpMessage='PlainText to Encrypt')]
[string]$plainText,
[Parameter(Mandatory=$true,Position=2,HelpMessage='GUID of Encryption Key in KMS')]
[string]$keyID,
[Parameter(Mandatory=$true,Position=3)]
[string]$region,
[Parameter(Position=4)]
[string]$AccessKey,
[Parameter(Position=5)]
[string]$SecretKey
)
{
# memory stream
[byte[]]$byteArray = [System.Text.Encoding]::UTF8.GetBytes($plainText)
$memoryStream = New-Object System.IO.MemoryStream($byteArray,0,$byteArray.Length)
# splat
$splat = @{Plaintext=$memoryStream; KeyId=$keyID; Region=$Region;}
if(![string]::IsNullOrEmpty($AccessKey)){$splat += @{AccessKey=$AccessKey;}}
if(![string]::IsNullOrEmpty($SecretKey)){$splat += @{SecretKey=$SecretKey;}}
# encrypt
$encryptedMemoryStream = Invoke-KMSEncrypt @splat
$base64encrypted = [System.Convert]::ToBase64String($encryptedMemoryStream.CiphertextBlob.ToArray())
return $base64encrypted
}
解密:
function Invoke-KMSDecryptText
(
[Parameter(Mandatory=$true,Position=1,HelpMessage='CipherText base64 string to decrypt')]
[string]$cipherText,
[Parameter(Mandatory=$true,Position=2)]
[string]$region,
[Parameter(Position=3)]
[string]$AccessKey,
[Parameter(Position=4)]
[string]$SecretKey
)
{
# memory stream
$encryptedBytes = [System.Convert]::FromBase64String($cipherText)
$encryptedMemoryStreamToDecrypt = New-Object System.IO.MemoryStream($encryptedBytes,0,$encryptedBytes.Length)
# splat
$splat = @{CiphertextBlob=$encryptedMemoryStreamToDecrypt; Region=$Region;}
if(![string]::IsNullOrEmpty($AccessKey)){$splat += @{AccessKey=$AccessKey;}}
if(![string]::IsNullOrEmpty($SecretKey)){$splat += @{SecretKey=$SecretKey;}}
# decrypt
$decryptedMemoryStream = Invoke-KMSDecrypt @splat
$plainText = [System.Text.Encoding]::UTF8.GetString($decryptedMemoryStream.Plaintext.ToArray())
return $plainText
}
他提供了一个例子:
Import-Module awspowershell
# set your credentials to access AWS, key you want to encrypt with, and the region the key is stored
$AccessKey = ''
$SecretKey = ''
$Region = 'eu-west-1'
$keyID = ''
$plainText = 'Secret'
# Encrypt some plain text and write to host
$cipherText = Invoke-KMSEncryptText -plainText $plainText -keyID $keyID -Region $Region -AccessKey $AccessKey -SecretKey $SecretKey
Write-host $cipherText
# Decrypt the cipher text and write to host
$plainText = Invoke-KMSDecryptText -cipherText $cipherText -Region $Region -AccessKey $AccessKey -SecretKey $SecretKey
Write-host $plainText