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

如何在.NET中实现等效于指定OpenSSL命令的RSA签名数据恢复?

.NET 实现 OpenSSL rsautl -verify 数据恢复方法

你提到的 OpenSSL 命令 openssl rsautl -verify -pubin -inkey public_key.pem -in signature.dat -out recovered_data.dat,本质是用公钥对签名数据执行 RSA 解密操作,以此恢复出原始数据(这种场景下的签名是直接用私钥加密原始数据生成的,而非标准的哈希签名)。在 .NET 中可以通过 RSA 类的解密方法实现,具体步骤如下:

核心逻辑

标准的 VerifyData 方法仅验证签名有效性,不会恢复原始数据;但因为你的场景是私钥加密原始数据生成签名,所以用公钥解密签名即可得到原始数据,这和 OpenSSL 命令的行为完全一致。

实现代码

1. 加载 PEM 格式公钥

using System;
using System.IO;
using System.Security.Cryptography;

public static RSA LoadPublicKeyFromPem(string pemFilePath)
{
    string pemContent = File.ReadAllText(pemFilePath);
    // 清理 PEM 格式的头部、尾部及换行符
    string publicKeyBase64 = pemContent
        .Replace("-----BEGIN PUBLIC KEY-----", string.Empty)
        .Replace("-----END PUBLIC KEY-----", string.Empty)
        .Replace("\r", string.Empty)
        .Replace("\n", string.Empty);
    
    byte[] publicKeyBytes = Convert.FromBase64String(publicKeyBase64);
    RSA rsa = RSA.Create();
    // 导入公钥(SubjectPublicKeyInfo 格式,对应 PEM 公钥)
    rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);
    return rsa;
}

2. 从签名中恢复原始数据

public static byte[] RecoverOriginalData(string publicKeyPemPath, byte[] signatureData)
{
    using (RSA rsa = LoadPublicKeyFromPem(publicKeyPemPath))
    {
        // 使用 PKCS#1 填充(OpenSSL rsautl 默认填充模式)
        return rsa.Decrypt(signatureData, RSAEncryptionPadding.Pkcs1);
    }
}

注意事项

  • 填充模式必须和生成签名时一致:如果生成签名时 OpenSSL 使用了 -raw 参数(无填充),则需要将解密时的填充改为 RSAEncryptionPadding.None。
  • 若公钥是其他格式(如 PKCS#8),需调整导入方法(比如用 ImportPkcs8PublicKey)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:17:51