Microsoft 如何将初始化向量添加到 Powershell 中 ConvertTo-SecureString 方法的 AES 加密中的安全字符串中?

问题描述 投票:0回答:1

我有几个加密文件,使用 Powershell 脚本使用 ConvertTo-SecureString 使用 AES-256 进行加密,如下所示:

$secretKey = "thisIsAnExampleButNotTheRealKey2"
$cleBytes = [System.Text.Encoding]::UTF8.GetBytes($secretKey)
$aes = New-Object System.Security.Cryptography.AesCryptoServiceProvider
$aes.Key = $cleBytes
$aes.GenerateIV()
$texteBytes = [System.Text.Encoding]::UTF8.GetBytes($texteAChiffrer)
$chiffreBytes = $aes.CreateEncryptor().TransformFinalBlock($texteBytes, 0, $texteBytes.Length)
$cryptedText = [Convert]::ToBase64String($chiffreBytes)
Write-Output "encrypted Text: $cryptedText"

在我的 C# 应用程序中,我必须解密这些文件。 我用的是这个方法:

public static string UncryptAES(string cryptedText, byte[] key, byte[] initVector)
{
  using (Aes aesAlgo = Aes.Create())
  {
    aesAlgo.Key = key;
    // how to compute the initVector instead of passing it as a parameter?
    aesAlgo.IV = initVector;
    ICryptoTransform decryptor = aesAlgo.CreateDecryptor(aesAlgo.Key, aesAlgo.IV);

    using (var msDecrypt = new MemoryStream(Convert.FromBase64String(cryptedText)))
    {
      using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
      {
        using (var srDecrypt = new StreamReader(csDecrypt))
        {
          return srDecrypt.ReadToEnd();
        }
      }
    }
  }
}

我读到,初始化向量是在加密完成后由 Powershell 生成的随机数,并与加密数据一起存储。 如何计算初始向量?

c# powershell cryptography
1个回答
0
投票

关于 IV 的一个有趣的事实是它并不是秘密。想想看:如果你加密几个数据块,每个块都是下一个块的 IV。您只需要使用第一个块(即 IV)来引导该过程。

为了让 IV 顺利通过,发送者和接收者必须:

  1. 同意给定值(通常只是 0),但这会导致 IV 重用(不好)
  2. 在不同的频道发送 IV(噩梦)
  3. 将 IV 与密文一起发送(通常是这样做的)

Powershell 不会对您将使用的方法做出任何假设,即使通过做正确的事情并为每个加密生成随机 IV,也排除了上面的选择 #1。

因此,要回答您的问题,只需编辑代码以在密文前面添加 IV,并在解密之前读回它即可。此示例 Powershell 代码通过在两个部分之间添加一个点

.
来实现此目的。

$texteAChiffrer = "Bonjour"
$secretKey = "thisIsAnExampleButNotTheRealKey2"
$cleBytes = [System.Text.Encoding]::UTF8.GetBytes($secretKey)
$aes = New-Object System.Security.Cryptography.AesCryptoServiceProvider
$aes.Key = $cleBytes
$aes.GenerateIV()
$texteBytes = [System.Text.Encoding]::UTF8.GetBytes($texteAChiffrer)
$chiffreBytes = $aes.CreateEncryptor().TransformFinalBlock($texteBytes, 0, $texteBytes.Length)
$cryptedText = [Convert]::ToBase64String($aes.IV) + "." + [Convert]::ToBase64String($chiffreBytes)
Write-Output "IV with encrypted Text: $cryptedText"

输出:

IV with encrypted Text: SN+W+25FCSj2Xl2Ys/nOaQ==.418V8h+95aqVHCBs2PxdFA==
© www.soinside.com 2019 - 2024. All rights reserved.