簡體   English   中英

Golang:使用與指定公鑰對應的私鑰驗證x509證書是否已簽名

[英]Golang: verify x509 certificate was signed using private key that corresponds to the specified public key

我希望驗證X509證書以確保它是由與公鑰對應的私鑰簽名的:

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

在我看來, certificate.CheckSignature方法是正確的方法,但我無法弄清楚它需要的參數,並希望得到社區的幫助。

順便說一句,我能夠在java中做同樣的事情(處理兩個相鄰的項目)。 它看起來像這樣:

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);

我很欣賞這個領域的任何暗示! P.

如果我理解你想要做什么,那么回答很簡單。

您的證書包含公鑰。 因此,您只需要將公鑰與證書中的公鑰進行比較。 代碼如下:

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")
}

更新

剛剛檢查了OpenJDK 實現的.verify方法 看起來可能存在證書不包含公鑰並且您確實需要驗證簽名的情況。 這種情況的Go代碼如下所示:

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")
}

謝謝Roman,我設法讓它像這樣工作:

hash := sha1.New()
hash.Write(certificate.RawTBSCertificate)
hashData := hash.Sum(nil)
rsa.VerifyPKCS1v15(dsPublicKey, crypto.SHA1, hashData, certificate.Signature)

所以,這基本上是你推薦的,但是使用了sha1哈希 - 這就是我在本地生成的證書所獲得的。 我還設法通過臨時交換證書的公鑰以及我想要驗證的密鑰來使其工作:

certificate.PublicKey = certificateAuthorityPublicKey
certificate.CheckSignature(x509.SHA1WithRSA, certificate.RawTBSCertificate, certificate.Signature) 

第二種方法看起來很糟糕,但它們都按預期工作......

想知道是否可以在運行時確定它是SHA1還是SHA256?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM