如何在X509证书中计算和插入签名

时间:2015-10-06 10:41:50

标签: cryptography digital-signature x509

我尝试执行TBSCertificate的指纹以便对其进行签名并将其插入x509证书中。我无法找到允许我单独执行的任何工具或库。

我可以创建一个x509证书并执行与openssl或许多库一样的签名,但它将直接包含在证书中,我需要在包含它之前修改签名。

你认识一个人吗?

1 个答案:

答案 0 :(得分:0)

我终于设法使用python的pyasn1库。

如果将来有人需要它,你可以在pyasn1邮件中谈论它:

https://sourceforge.net/p/pyasn1/mailman/message/34523982/

和我的个人解决方案:

from M2Crypto import X509, EC, EVP
from hashlib import sha256
from pyasn1_modules.rfc2314 import Signature
from pyasn1_modules.rfc2459 import Certificate
from pyasn1.codec.der import encoder, decoder

csr = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNyakNDQVpZQ0FRQXdEUVlKS29aSWh2Y05BUUVMQlFBd2dZWXhDekFKQmdOVkJBWVRBa05VTVJJd0VBWUQKVlFRSURBbENZWEpqWld4dmJtRXhFekFSQmdOVkJBY01Da0psYkd4aGRHVnljbUV4RVRBUEJnTlZCQW9NQ0ZCaAplVk5sYm5ObE1Rd3dDZ1lEVlFRTERBTkJRMEV4RERBS0JnTlZCQU1NQTBGRFFURWZNQjBHQ1NxR1NJYjNEUUVKCkFSWVFZV05oUUdSbGFXTXVkV0ZpTG1OaGREQWVGdzB4TlRFd01EZ3dPVFF4TURKYUZ3MHhOakV3TURjd09UUXgKTURKYU1JR0FNUXN3Q1FZRFZRUUdFd0pEVkRFU01CQUdBMVVFQ0F3SlFtRnlZMlZzYjI1aE1STXdFUVlEVlFRSApEQXBDWld4c1lYUmxjbkpoTVF3d0NnWURWUVFLREFOVlFVSXhEVEFMQmdOVkJBc01CRVJGU1VNeEt6QXBCZ05WCkJBTU1JbTF0VjFGVlFsbFpWMVJ2V2xwTmNIYzBjR0ZXVG5NeVRXNXZTbE5oUlZkUmVua3dWakFRQmdjcWhrak8KUFFJQkJnVXJnUVFBQ2dOQ0FBUjVJTWU2aDJwUlpwM201b25VcWloeGwyNkFIQjhMR01WZCtMWUNFTUl4V2U1ZQpySVJmcDA5bHNPUjB3L1B3T3N0bzRXSWFYOXFPSnBTb2JwZFlYRnJaTUEwR0NTcUdTSWIzRFFFQkN3VUFBNElCCkFRQXdHZVl3bkM5MmErR1g3VXE4N1k5Z3hXdFVKUWZiUlRwbXdCV1NPdmNlS3Z2Ky9zV3o5VFRqSGRKbElqVnYKbkQ5RHY5aHVlQUVONkE3Sm43SE80ZDhwelJ2d3pQSU5peXN4TUlzaWsxbldpTTRieTBLSDh4bE5SZEFoc3ZZTApVQ3hLSXVGMm1sUytJRGVtMUQyZE96L3ZFZlcrZVE4NVhsSVRycExpMFZlY3d5NnhwejNMN2R2SEdTOFJ1aVlyCkxkS1J3VnVGYmI4QmRHdVJ3dHgwNCtEeGJFKzlUb3hHSmFiM1VaV1loV3ByekcyS2owV0pORW44UlBwWXJjb2sKY3lBSTh4OFh0TDUrZUs5aklpV1NlcHIzcU9Zc3V6V2NqZ2VIeUdCUHNqN1lRQ2ZuWVFTbHBJMzJHRnZ5YWRmTApmRmZXSExxZE9nQmVET2JwenlaVDlyazkKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=="

cert = X509.load_cert_string(b64decode(csr))
ca_pkey = EVP.load_key(ACA_KEY)

asn1_cert = decoder.decode(cert.as_der(), asn1Spec=Certificate())[0]
tbs = asn1_cert.getComponentByName("tbsCertificate")

tbs_der = encoder.encode(tbs)

digest = sha256()
digest.update(tbs_der)
signature = ca_pkey.get_rsa().sign(digest.digest(), "sha256")

# Take the raw signature and turn it into a BitString representations (special thanks to Alex <ralienpp@gmail.com>)
bin_signature = Signature("'%s'H" % ''.join("%02X" % ord(c) for c in signature))

asn1_cert.setComponentByName("signatureValue", bin_signature)

# Check that both certificates matches
cert.sign(ca_pkey, md='sha256')
print cert.as_text()

print encoder.encode(asn1_cert) == cert.as_der()

初始csr是BER的base64编码X509证书。

重要的是要强调csr已经包含正确的签名算法。