C# - 从 PDF 签名获取公钥

标签 c# pdf ssl certificate

用例如下:

  1. 用户进入需要出示证书的网站
  2. 如果有效,用户可以下载 PDF 并使用相同的证书对其进行签名
  3. 上传 PDF
  4. 服务器验证 PDF 是由提供给网站的同一证书签名的。

我卡在了第 4 步。我已经设法从网站和 PDF 中获取了客户端证书公钥,但两者并不相同。公钥是 2048 位的 SHA256 RSA。此外,我正在使用 iTextSharp 来处理 PDF 文档。

这是我的代码:

 HttpRequest request = context.Request;

 HttpClientCertificate cert = request.ClientCertificate;

 //get public key from client certificate
 string certKey = BitConverter.ToString(cert.PublicKey).Replace("-", " ")

 //now gets PDF and retrieves public key
 PdfReader pdfreader = new PdfReader("path_to_pdf");


 AcroFields fields = pdfreader.AcroFields;
 AcroFields.Item item = fields.GetFieldItem("Signature1");
 List<string> names = fields.GetSignatureNames();

 foreach (string name in names){
     PdfDictionary dict = fields.GetSignatureDictionary(name);
     PdfPKCS7 pkcs7 = fields.VerifySignature(name);
     Org.BouncyCastle.X509.X509Certificate cert = pkcs7.SigningCertificate;

     //get public key from PDF cert
     SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cert.GetPublicKey());
     byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
     string serializedPublic = BitConverter.ToString(serializedPublicBytes).Replace("-", " ");
 }

有了这段代码,certKey 和 serializedPublic 就不一样了。

最佳答案

在你的代码中你比较

  • 来自证书 (HttpClientCertificate.PublicKey) 的公钥二进制值
  • SubjectPublicKeyInfo 对象 (publicKeyInfo.ToAsn1Object().GetDerEncoded()) 的二进制值,它包装了公钥及其算法。

因此,后者可能包含前者,但不重合

SubjectPublicKeyInfo 定义如下:

SubjectPublicKeyInfo ::= SEQUENCE {
    algorithm AlgorithmIdentifier,
    publicKey BIT STRING
}

因此,您不应与完整的 SubjectPublicKeyInfo 对象的二进制表示进行比较,而应与包含的公钥的二进制表示进行比较:

publicKeyInfo.PublicKeyData.GetBytes()

关于C# - 从 PDF 签名获取公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43897049/

相关文章:

apache - 使用 IE8 无法通过 SSL 加载网站

c# - 为什么编译器找不到我的方法?

用于创建 CA 的 C# 实用程序

java - 错误: open failed: ENOENT (No such file or directory) add gallery image in document pdf

禁用 HTTPS 的通用名称检查的安全隐患

c# - 根据验证程序,远程证书无效

c# - 使用静态类的 2 个单元测试 c# 之间的冲突

c# - 使用功能区创建 Windows 应用程序

java - 出现异常.NoClassDefFoundError : com/itextpdf/text/log/CounterFactory

java - PDFBox 将 PDF 转换为 TIFF。减少图像大小(以字节为单位)