0

任何人都可以帮助我使用 AWS KMS 加密/解密文件夹中文件的内容吗?我希望 powershell 脚本也能做到这一点。我想在上传到亚马逊 s3 存储桶之前加密文件夹,并想在从 s3 存储桶下载后解密它。

PS:我是PowerShell脚本的新手。

提前致谢!

4

1 回答 1

0

你可以从 steven那里找到一个很好的教程。

我只是复制粘贴他对我来说非常有用的代码。

加密:

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
于 2016-08-24T20:58:14.167 回答