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

PowerShell加密敏感数据存磁盘 解密使用时凭据无效求助

问题根因

  • 密钥存取的类型与编码错误:直接使用Out-File存储字节数组类型的$key时,PowerShell会默认将字节转为字符串后用UTF-16(Unicode)编码写入,读取时Get-Content默认返回字符串数组而非原始字节数组,导致解密密钥和加密密钥完全不一致。
  • 密钥生成逻辑错误:如果目标$KeyFile已存在,代码仅执行了读取操作,没有将读取到的内容赋值给当前$key变量,后续加密用的是本次新生成的随机密钥,解密时读取的是旧文件中的密钥,二者不匹配。
  • 路径变量不一致:加密用户名时写入的路径是$file,但解密时读取的路径是$SecureName,如果两个变量值不相等,会读取到错误的加密用户名内容。
  • 加密内容读取无编码指定:Get-Content读取加密后的字符串时如果编码不匹配,也会导致解密失败。

修复方案

1. 密钥生成与存储逻辑修复

# 提前为$KeyFile赋值自定义密钥存储路径
$KeyFile = "C:\Custom\Path\AESKey.dat"
try
{
    [Byte[]]$key = New-Object Byte[] 32
    if (Test-Path $KeyFile)
    {
        # 直接读取字节流,不经过字符串转码
        $key = [System.IO.File]::ReadAllBytes($KeyFile)
    }
    else
    {
        # 生成32位随机AES密钥
        [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
        # 直接写入字节流到文件,避免编码损耗
        [System.IO.File]::WriteAllBytes($KeyFile, $key)
        attrib +s +h $KeyFile
    }
}
catch
{
    $ectp, $msg = $_.Exception.Message.split(':')
    InfoWrite("config: error: $($msg)")
    WriteEventLog -eventString "config: error: $($msg)" -entryType Error
}

2. 敏感数据加密逻辑修复

# 提前定义$SecureName(加密用户名存储路径)、$SecurePass(加密密码存储路径)
# 加密用户名
ConvertTo-SecureString $UserNameTextBox.Text -AsPlainText -Force | ConvertFrom-SecureString -Key $key | Set-Content -Path $SecureName -Force -Encoding UTF8
# 加密密码
ConvertTo-SecureString $PasswordTextBox.Text -AsPlainText -Force | ConvertFrom-SecureString -Key $key | Set-Content -Path $SecurePass -Force -Encoding UTF8

3. 解密构造凭据逻辑修复

# 读取密钥
$key = [System.IO.File]::ReadAllBytes($KeyFile)
# 解密用户名
$secureUserName = Get-Content $SecureName -Encoding UTF8 | ConvertTo-SecureString -Key $key
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureUserName)
$UserName = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) # 释放内存避免敏感数据泄露
# 解密密码
$securePassword = Get-Content $SecurePass -Encoding UTF8 | ConvertTo-SecureString -Key $key
# 构造凭据对象
$global:UserCredential = New-Object System.Management.Automation.PSCredential ($UserName, $securePassword)

修复完成后重新执行AD查询测试即可正常通过校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 14:54:05