質問

I am struggling to port the following java code to python. I am using PyCrypto to read the publickKey but it fails with an 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

These are the variables:

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

message = "2425605254855826526"

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

and this is the code in Java that verifies the signature.

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));
役に立ちましたか?

解決

There is a specific class method called importKey in PyCrypto to read in DER or PEM encoded RSA keys.

from base64 import b64decode
from Crypto.PublicKey import RSA

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

If your key is not a simple DER, but a full X.509 certificate, see this other StackOverflow answer. Once you have keyPub, you can verify the signature like this:

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top