duanbei1709 2017-03-02 15:44
浏览 550
已采纳

Golang:验证x509证书是否使用与指定公钥相对应的私钥签名

I want to get an X509 certificate verified to make sure it was signed by the private key that corresponds to the public key:

var publicKey *rsa.PublicKey = getPublicKey()
var certificate *x509.Certificate = getCertificate()
certificate.CheckSignature(...)

It seems to me that certificate.CheckSignature method is the right way to go but I can not figure out the parameters it needs and would like to ask for community's help.

Btw, I was able to do the same in java (working on two adjacent projects). It looks like this:

RSAPublicKey publicKey = getPublicKey();
X509Certificate certificate = X509CertUtils.parse(...);

// Verifies that this certificate was signed using the
// private key that corresponds to the specified public key.
certificate.verify(publicKey);

I appreciate any hints on the field! P.

  • 写回答

2条回答 默认 最新

  • dongzipu7517 2017-03-03 06:18
    关注

    If I properly understood what you are trying to do, then answer is simple.

    Your certificate includes the public key. So all you need is to compare your public key with the public key from the certificate. The code looks like:

    if certificate.PublicKey.(*rsa.PublicKey).N.Cmp(publicKey.(*rsa.PublicKey).N) == 0 && publicKey.(*rsa.PublicKey).E == certificate.PublicKey.(*rsa.PublicKey).E {
        println("Same key")
    } else {
        println("Different keys")
    }
    

    Update

    Just checked OpenJDK implementation of .verify method. Looks like there can be situation when certificate doesn't contain the public key and you actually need to verify signature. The Go code for this case looks like this:

    h := sha256.New()
    h.Write(certificate.RawTBSCertificate)
    hash_data := h.Sum(nil)
    
    err = rsa.VerifyPKCS1v15(publicKey.(*rsa.PublicKey), crypto.SHA256, hash_data, certificate.Signature)
    if err != nil {
        println("Signature does not match")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建