无法使用PKI验证python中的签名

时间:2013-04-26 07:30:35

标签: python rsa pycrypto m2crypto

我正在努力将以下java代码移植到python。我正在使用PyCrypto来读取publickKey,但是它因assertionError而失败:

keyDER = b64decode(publicKeyBase64)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct( (seq[0], seq[1]) )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 539, in construct
    key = self._math.rsa_construct(*tup)
  File "/usr/local/lib/python2.7/site-packages/Crypto/PublicKey/_slowmath.py", line 84, in rsa_construct
    assert isinstance(n, long)
AssertionError

这些是变量:

signature = "cIUiufopX990NUXlVUznzf3\/gBwhXol2ligPdGp7CHrZNAdDzkDj5pQoikj2sKFiRACEA STh gE4oKJwRAC7Qz1NsNHWCkIYZPAwX\/95sHiVmNiqfXIowm9cqLWyL XLJwkmQupNoTauYWiEm1YF904LyI4hecNST4H4lNcl68="

message = "2425605254855826526"

publicKeyBase64="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVicPgYOx7mDPYDtq4kj24uRfIdNVxjMp9DNlsvmDr9ojrDBn+Ue1YdxYb/rBlDFYab57ClhzOgZjdmUv3T3WKKXE8To9tN2PG/bYEkZpBxn6M1vl0mrp/l6WbyUH4oXUx4kQAeM8/XXZdymbg8S6oLeWT1YrAj6k15fWpSMN0qQIDAQAB"

这是Java中用于验证签名的代码。

import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

verifySignature(String message, String signature, String publicKeyBase64 )    

    byte[] keyBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(publicKeyBase64);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    pubKey = (RSAPublicKey) fact.generatePublic(spec);

    Signature genSignature = Signature.getInstance("SHA1withRSA");
    genSignature.initVerify(pubKey);
    genSignature.update(message.getBytes("UTF-8"));
    boolean result = genSignature.verify(javax.xml.bind.DatatypeConverter.parseBase64Binary(signature));

1 个答案:

答案 0 :(得分:1)

PyCrypto中有一个名为importKey的特定类方法,用于读取DER或PEM编码的RSA密钥。

from base64 import b64decode
from Crypto.PublicKey import RSA

publicKeyBase64="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVicPgYOx7mDPYDtq4kj24uRfIdNVxjMp9DNlsvmDr9ojrDBn+Ue1YdxYb/rBlDFYab57ClhzOgZjdmUv3T3WKKXE8To9tN2PG/bYEkZpBxn6M1vl0mrp/l6WbyUH4oXUx4kQAeM8/XXZdymbg8S6oLeWT1YrAj6k15fWpSMN0qQIDAQAB"
keyDER = b64decode(publicKeyBase64)
keyPub = RSA.importKey(keyDER)

如果您的密钥不是简单的DER,而是完整的X.509证书,请参阅this other StackOverflow answer。 获得keyPub后,您可以像这样验证签名:

from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA

verifier = PKCS1_v1_5.new(keyPub)
h = SHA.new(message)
result = verifier.verify(h, signature)