2014-01-07 46 views
2

我對安全性沒有太多經驗,但現在我必須在python中實現簽名過程。無法使用python中的X509Certificate簽署數據

我有一個證書somename.cer。我有一個如何如下我簽字串與串的c#實現的例子:

CertColl是證書的集合,其中相關的代碼發現與上線Thumbprint相關證書,並返回證書的列表。

X509Certificate2 cert = certColl[0] 
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey; 
return Convert.ToBase64String(rsa.SignData(Encoding.GetEncoding(1251).GetBytes(my_string), new SHA1CryptoServiceProvider())); 

my_string是要簽名和代碼內構造的字符串,但我並不需要增加在這裏

這些步驟,所以我試圖用this previous Q&A

幫助實現這個在Python
from Crypto.Util.asn1 import DerSequence 
from Crypto.PublicKey import RSA 
from binascii import a2b_base64 

pem = open("some-path/somefile.cer") # I have a certificate with `cer` extension 
lines = pem.replace(" ",'').split() 
der = a2b_base64(''.join(lines[1:-1])) 

cert = DerSequence() 
cert.decode(der) 
tbsCertificate = DerSequence() 
tbsCertificate.decode(cert[0]) 
subjectPublicKeyInfo = tbsCertificate[6] 

rsa_key = RSA.importKey(subjectPublicKeyInfo) 

正如我所料,現在我可以用這個簽署my_string

rsa_key.sign("Hello World", "") 

但我收到以下錯誤:

TypeError: Private key not available in this object

難道我做錯了什麼,像usnig錯誤的方法來模仿蟒蛇rsa.SignData

回答

2

您的證書不包含私鑰。

從我在C#代碼中看到的內容中,我猜你正在從Windows證書存儲中獲取證書。該商店可以包含帶和不帶私鑰的證書。

.cer另一方面,(通常)文件不包含私鑰 - 它們只有公鑰。這就是爲什麼用它簽名是不可能的。

我猜你已經從Windows證書存儲導出了.cer文件,並沒有選擇「導出私鑰」選項。您應該通過以.pfx.pvk格式重新導出它並嘗試使用該文件簽名來獲得更好的運氣。

See more on this topic here