在Python中验证SHA1withRSA?

时间:2017-03-28 02:09:48

标签: java python rsa digital-signature pycrypto

我想将Java代码重写为Python。代码用于通过.cer文件验证数据。

public static boolean verifyByRSA(String certPath, byte[] aPlainData,
        byte[] aSignature) {
    boolean tResult = false;
    try {
        InputStream inStream = new FileInputStream(certPath);
        CertificateFactory tCertFactory = CertificateFactory
                .getInstance("X.509");
        Certificate tCertificate = tCertFactory
                .generateCertificate(inStream);

        Signature tSign = Signature.getInstance("SHA1withRSA", "BC");
        tSign.initVerify(tCertificate);

        tSign.update(aPlainData);
        tResult = tSign.verify(aSignature);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return tResult;
}

.cer文件就像:

-----开始证书----- MIIDhzCCAm + gAwIBAgIGASYISh96MA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDElMCMGA1UECwwcQWxsaW5wYXkgUHJpbWFyeSBDZXJ0aWZpY2F0ZTAeFw0xMDAxMDcxMDE3NDBaFw0zMDAxMDIxMDE3NDBaMGQxCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDEqMCgGA1UECwwhQWxsaW5wYXkgRGlnaXRhbCBTaWduIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEv2q2 / xN5PF0dLn1vhIaVlyWsvJFVFxWgH7sQBObzYbZXOOVzoQpmXuSFOrF0 / ol4Okd / 2OGfdXUUFSUZfzAQOT1Wmjupec7z2V6l4 / PT7aOg6t / MJwU9aW9Iw + AFzM1vnLOXdTlWVLZbtB7IiJ / HhfwBDkyvhp1zNYoAPrwC5QIDAQABo4HHMIHEMB0GA1UdDgQWBBQlWQA // YbuEdfE1yP + PpnokDO8WDCBjgYDVR0jBIGGMIGDgBSBWR3Bvx8To7TrecKhCM4smeabN6FjpGEwXzELMAkGA1UEBhMCQ04xKTAnBgNVBAoMIEFsbGlucGF5IE5ldHdvcmsgU2VydmljZXMgQ28uTHRkMSUwIwYDVQQLDBxBbGxpbnBheSBQcmltYXJ5IENlcnRpZmljYXRlggYBJghKHowwEgYDVR0TAQH / BAgwBgEB / wIBADANBgkqhkiG9w0BAQUFAAOCAQEATzT9GuAmAXLSWpoGc0F7Km7DPMWvSAkq8ckJLftF0 / lB3JTR6QT5rsTnQHCdRU7SJX + eLNwhJQdRg34dPJAI2z / HpgGu7tW7pdsHjCjlVae3I64h2OzYBGXdtdRyPmyXfBOg XUfqtH0Fg + 1QqsRmcRugywjZH8ZQAVYm0TkVJmdBknPp60bJ2gE / nj0w6VaSL6HMAQ + A7AVne3NDreBXepMHgiFqiqMHrZFBQCgTSR1UwZoT8hwXaaUgwf2h9l / D2QOGCD8G3sRKfMsH3clkehXbprWPNk3uww7dCT0pGz845AyKzCmRK60Z / NOgMG5X + F + JmugsS / bKYwjetXHg9Q == -----结束证书-----

我试过了

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

key = RSA.importKey(open(cer_path).read())
signer = PKCS1_v1_5.new(key)
digest = SHA.new()
digest.update(str_to_sign)
if signer.verify(digest, base64.decodestring(signature)):
    return True
return False  

但是无法获得正确的结果.java代码意味着什么?

1 个答案:

答案 0 :(得分:1)

importKey功能支持以下内容:

  • X.509 subjectPublicKeyInfo DER SEQUENCE(二进制或PEM编码)
  • PKCS#1 RSAPublicKey DER SEQUENCE(二进制或PEM编码)
  • OpenSSH(仅限文本公钥)

现在只有第一个和第二个是X.509证书的 part

您需要一个库来解析X.509证书,例如the cryptography package

作为权宜之计,您可以在Java代码中获取RSAPublicKey对象并调用getEncoded。这将返回带有subjectPublicKeyInfo的DER SEQUENCE,可以在Python crypto中导入(importKey函数支持的第一种格式)。