You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell字符串加解密结果异常,求解决方法

问题分析

你的代码核心错误在于解密流程逻辑颠倒,且未正确将SecureString转换为明文:

  1. 加密流程是正确的:明文→ConvertTo-SecureString(转为SecureString)→ConvertFrom-SecureString -Key(生成加密字符串)
  2. 解密时操作逻辑完全搞反,还错误重复调用ConvertFrom-SecureString,导致输出的是加密后的字符串而非明文
  3. SecureString本身是加密存储的,无法直接用Write-Host输出,必须转换为普通字符串
修正后的代码
$encryptionKey = (13, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
$stringToEncrypt = "Hello World"

# 加密流程:明文 → SecureString → 加密字符串 → 写入文件
$encryptedString = $stringToEncrypt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key $encryptionKey
$encryptedString | Out-File -FilePath key.txt

# 解密流程:读取加密字符串 → SecureString → 明文
$encryptedContent = Get-Content key.txt -Raw
$secureString = ConvertTo-SecureString $encryptedContent -Key $encryptionKey
# 用原生NetworkCredential类转换SecureString为明文,无需加载额外类型
$decryptedString = [System.Net.NetworkCredential]::new("", $secureString).Password

Write-Host $decryptedString # 输出:Hello World
关键说明
  • 解密时必须用ConvertTo-SecureString -Key将加密字符串转回SecureString,而非再次调用ConvertFrom-SecureString
  • [System.Net.NetworkCredential]是PowerShell原生支持的类,不需要调用Add-Type或引入Security.Cryptography命名空间,完全适配你的环境限制
  • 读取文件时添加-Raw参数,避免换行符干扰解密过程

内容的提问来源于stack exchange,提问作者Samor1922

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 04:30:49