2013-04-26 67 views
0

我正努力將以下java代碼移植到python。我使用PyCrypto閱讀publickKey但它失敗,一個AssertionError:無法使用PKI驗證python中的簽名

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

有稱爲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)