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

私钥签名哈希字节数组写入文本文件后无法还原验签的问题问询

解决方案

核心还原逻辑

你写入文件的操作是「原始签名字节 → Base64字符串 → UTF8编码字节」,还原只需要反向操作即可:

  1. 读取文本文件得到的字节数组,先通过UTF8解码得到Base64字符串
  2. 对Base64字符串做解码,即可得到原始的签名哈希字节数组

具体实现代码

public static byte[] ConvertFromBase64(byte[] fileReadBytes)
{
    // 第一步:将读取到的UTF8字节转成Base64字符串
    string base64Str = Encoding.UTF8.GetString(fileReadBytes);
    // 第二步:解码Base64得到原始签名字节
    return Convert.FromBase64String(base64Str);
}

验证流程示例

// 1. 读取存储签名的文本文件得到字节数组
byte[] fileContent = File.ReadAllBytes("你的签名文件路径.txt");
// 2. 还原得到原始签名字节
byte[] originalSignature = ConvertFromBase64(fileContent);
// 3. 计算待验证文件的哈希
byte[] fileHash = GetHashSha256FromFile("待验证的文件路径");
// 4. 调用验证方法
bool verifyResult = verifyData(fileHash, originalSignature);
// 5. 查看结果
Console.WriteLine(verifyResult ? "签名验证通过" : "签名验证失败");

额外优化建议

  • 你现有的verifyData方法中错误提示有误,公钥验证场景不存在私钥,建议将异常信息修改为"Not an ECDSA cert, or has no public key"
  • SHA256实现类是非线程安全的,且实现了IDisposable接口,不建议全局复用实例,建议修改GetHashSha256FromFile方法,每次计算哈希时单独创建实例:
//  Compute the file's hash.
private byte[] GetHashSha256FromFile(string filename)
{
    using (SHA256 sha256 = SHA256.Create())
    using (FileStream stream = File.OpenRead(filename))
    {
        return sha256.ComputeHash(stream);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:15:06