我在安全方面没有太多经验,但现在我需要在Python中实现一种签名程序。
我有一个证书somename.cer
。我有一个实现示例,如何使用该字符串对我的字符串进行签名:
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
是在代码中要签名和构建的字符串,但我不需要在这里添加这些步骤。
因此,我正在尝试使用这个之前的问答来在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: 对象中没有可用的私钥
我做错了什么吗?比如在 Python 中使用错误的方法来模仿 rsa.SignData 吗?