已成功加密 $PROFILE 文件,但无法取回准确的解密 $PROFILE 文件

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

我的 Windows 11 系统中安装了 Powershell 5.x。我在 Powershell $PROFILE 全局脚本中存储了一些安全密钥,以便轻松运行 GitHub 等命令。

现在我已经成功加密(并保护)了 $PROFILE 文件并将其通过此函数存储在

$PROFILE.cryptd
路径中:


function Encrypt-Profile {
  # Paths for the profile file and the encrypted profile
  $ProfilePath = $PROFILE
  $CryptdProfilePath = "$PROFILE.cryptd"

  # Read the plaintext profile file
  $plainText = Get-Content -Path $ProfilePath -Raw

  # Convert the text into a secure string
  $secureString = ConvertTo-SecureString -String $plainText -AsPlainText -Force

  # Encrypt the secure string and convert it to a string representation
  $encryptedText = $secureString | ConvertFrom-SecureString

  # Save the encrypted text to a file
  Set-Content -Path $CryptdProfilePath -Value $encryptedText
  Write-Host "Profile encrypted and saved to $CryptdProfilePath"
}

但是当我尝试反转

Decrypt-Profile
函数中的步骤时(假设完全反转上述函数并返回路径
$PROFILE.plaintxt
处解密的明文 $PROFILE),它反而在第二行本身抛出错误:

ConvertTo-SecureString : Input string was not in a correct format.

我使用的

Decrypt-Profile
功能是:

function Decrypt-Profile {
  # Paths for the profile file and the encrypted profile
  $ProfilePath = "$PROFILE.cryptd"
  $PlainTxtProfilePath = "$PROFILE.plaintxt"

  # Read the encrypted text from the file
  Echo "$PROFILE.cryptd"
  $encryptedText = Get-Content -Path $ProfilePath -Raw

  # Convert the encrypted text back into a secure string
  $secureString = $encryptedText | ConvertTo-SecureString

  # Convert the secure string back into plain text
  $decryptedText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
  )

  # Display the decrypted profile content
  # Write-Host "Decrypted Profile Content:"
  # Write-Host $decryptedText

  Set-Content -Path $PlainTxtProfilePath -Value $decryptedText
  Write-Host "Profile decrypted and saved to $PlainTxtProfilePath"
}

如果我在读取加密文件的内容期间执行

ConvertFrom-SecureString
(如上面解密函数中的
$encryptedText = Get-Content -Path $ProfilePath -Raw | ConvertFrom-SecureString
),我会收到错误:

ConvertFrom-SecureString : The input object cannot be bound to any parameters for the command either because the command does not
take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

我在

Decrypt-Profile
做错了什么?我想如果我完全颠倒步骤的话,这就会进进出出。

powershell encryption securestring
1个回答
0
投票
当您第一次将加密字符串写入磁盘时,

Set-Content
添加尾随换行符 - 在将内容读回内存时使用
String.Trim()
删除它:

  $encryptedText = Get-Content -Path $ProfilePath -Raw |ForEach-Object Trim
© www.soinside.com 2019 - 2024. All rights reserved.