PowerShell字符串加解密结果异常,求解决方法
问题分析
你的代码核心错误在于解密流程逻辑颠倒,且未正确将SecureString转换为明文:
- 加密流程是正确的:明文→ConvertTo-SecureString(转为SecureString)→ConvertFrom-SecureString -Key(生成加密字符串)
- 解密时操作逻辑完全搞反,还错误重复调用ConvertFrom-SecureString,导致输出的是加密后的字符串而非明文
- 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
相关产品推荐
相关产品推荐

