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

PowerShell加密标准字符串后C#解密报错求助

PowerShell加密字符串后C#解密失败的解决方法

问题场景

在PowerShell中使用指定密钥加密密码字符串,代码如下:

$pwd = Read-Host -Prompt "Entrez le mot de passe" 
$securePwd = ConvertTo-SecureString $pwd -AsPlainText -Force 
$encryptedPwd = ConvertFrom-SecureString -SecureString $securePwd -Key (1..16) 
$encryptedPwd | Out-File -FilePath $svcAccountPath 

尝试用C#读取加密后的文件并解密时,在ProtectedData.Unprotect行报错,原C#代码:

static SecureString DecryptPassword(byte[] key, string filePath)
{
    byte[] encryptedData = File.ReadAllBytes(filePath);
    byte[] decryptedData = ProtectedData.Unprotect(encryptedData, key, DataProtectionScope.CurrentUser);

    SecureString decryptedPassword = new SecureString();
    foreach (byte b in decryptedData)
    {
        decryptedPassword.AppendChar((char)b);
    }

    return decryptedPassword;
}
static string DecryptSecureString(SecureString secureString)
{
    IntPtr unmanagedString = IntPtr.Zero;
    try
    {
        unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
        return Marshal.PtrToStringUni(unmanagedString);
    }
    finally
    {
        Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
    }
}
private void idk()
{
    string pwdSeduredFile = "C:/Temp/C01 User Manager/conf/encryptedPwd.txt";
    byte[] key = new byte[16];
    for (int i = 0; i < 16; i++)
    {
        key[i] = (byte)(i + 1);
    }
    SecureString encryptedPassword = DecryptPassword(key, pwdSeduredFile);
    string password1 = DecryptSecureString(encryptedPassword);
    MessageBox.Show("password :" + password1, "Erreur", MessageBoxButton.OK, MessageBoxImage.Information);
}

错误原因

PowerShell的ConvertFrom-SecureString -Key命令输出的是Base64编码的字符串,而非原始二进制加密数据。原C#代码直接用File.ReadAllBytes读取文件,获取的是文本文件的编码字节(比如UTF-8),并非解密所需的二进制加密数据,导致ProtectedData.Unprotect无法识别格式而报错。

修正后的C#代码

仅需修改DecryptPassword方法,先读取文件内容为文本,再将Base64字符串解码为二进制数组:

static SecureString DecryptPassword(byte[] key, string filePath)
{
    // 读取Base64编码的加密字符串
    string encryptedBase64 = File.ReadAllText(filePath).Trim();
    // 将Base64字符串转换为二进制加密数据
    byte[] encryptedData = Convert.FromBase64String(encryptedBase64);
    // 解密数据
    byte[] decryptedData = ProtectedData.Unprotect(encryptedData, key, DataProtectionScope.CurrentUser);

    SecureString decryptedPassword = new SecureString();
    foreach (byte b in decryptedData)
    {
        decryptedPassword.AppendChar((char)b);
    }

    return decryptedPassword;
}

其余代码保持不变即可正常解密。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:00:07