Python:使用.Cer文件打开以获取公钥,然后执行验证 [英] Python: open with .Cer file to get public key and then perform verification

查看:200
本文介绍了Python:使用.Cer文件打开以获取公钥,然后执行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含公共密钥的.cer文件.我需要使用此文件来验证由相应私钥签名的签名.我有签名和公钥.我需要验证签名.我得到的结果是错误的.下面是代码:

I have a .cer file containing public key. I need to use this file to verify signature signed by corresponding private key. I have the signature and public key. I need to verify the signature. I'm getting result as false. Below is the code:

def verify_sign(public_key_loc, signature, data):
    '''
    Verifies with a public key from whom the data came that it was indeed
    signed by their private key
    param: public_key_loc Path to public key
    param: signature String signature to be verified
    return: Boolean. True if the signature is valid; False otherwise.
    '''
    #pdb.set_trace()
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from base64 import b64decode
    try:
        pub_key = open(public_key_loc, "r").read()
        rsakey = RSA.importKey(pub_key)
        signer = PKCS1_v1_5.new(rsakey)
        digest = SHA256.new()
        # Assumes the data is base64 encoded to begin with
        digest.update(b64decode(data))
        if signer.verify(digest, b64decode(signature)):
            return True
        return False 
    except Exception as e:
        print e

我试图在这里使用方法将.cer文件转换为.pem.如何在PyCrypto中使用X509证书?

I tried to use method here to convert .cer file to .pem. How do I use a X509 certificate with PyCrypto?

这里使用的方法是否正确?还是python有更好的库.因为据我所知,python不支持X.509Certificate.用我的英语.感谢任何帮助.

Is the method used here is correct? or does python has better libraries. Because as far as i know, python does not support X.509Certificate. Bear my english. Appreciate any help.

谢谢.

截至目前,我正在尝试使用Pycrypto.我是否需要在同一pycrypto中使用其他任何库或方法?

As of now, i'm trying to use Pycrypto. Do i need to use any other libraries or method in the same pycrypto?

推荐答案

您应该能够使用 openssl x509 命令从X509证书中提取公钥组件.您说您的证书文件具有 .cer 扩展名,这通常意味着二进制DER格式,因此此命令应以pycrypto可以使用的形式提取公钥:

You should be able to extract the public key component from the X509 certificate using the openssl x509 command. You say that your certificate file has a .cer extension which often means a binary DER format, so this command should extract the public key in a form that can be used by pycrypto:

openssl x509 -inform der -pubkey -noout -in certificate.cer >public_key.pem

尽管如此,您的 .cer 文件可能已经是PEM格式(我怀疑这是因为在C#中,您需要base64对该证书进行解码),在这种情况下,此命令应获取公钥:

Although, it's possible that your .cer file is already in PEM format (I suspect that it is because in C# you needed to base64 decode this certificate), in which case this command should get the public key:

openssl x509 -pubkey -noout -in certificate.cer >public_key.pem

无论哪种方式,您都应该以类似于以下PEM格式密钥的文件 public_key.pem 结尾:

Either way you should end up with a file public_key.pem that resembles this PEM format key:


-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq8ZtNvMVc3iDc850hdWu
7LLw4CQfE4O4IKy7mv6Iu6uhHQsfRQCqSbc1Nwxq70dMudG+41cSBI2Sx7bsAby2
2seBOCCtcoXmDvyBbAetaHY4xUTXzMZKxZc+ZPRR5vB+suxW9yWCTUmYyxaY3SPx
iZHRF5dAmSbW4qIrXt+9ifIbGlMtzFBBetA9KgxVcBQB6VhJEHoLk4KL4R7tOoAQ
gs6WijTwzNfTubRQh1VUCbidQihVAOWMNVS/3SWRRrcN5V2DqOWL+4TkPK522sRD
K1t0C/i+XWjxeFu1zn3xXZlA2sruOIFQvpihbLgkrfOvjA/XESgshBhMfbXZjzC1
GwIDAQAB
-----END PUBLIC KEY-----

现在您可以使用 Crypto.PublicKey.RSA.importKey()加载它.

Now you can load this using Crypto.PublicKey.RSA.importKey().

您还应该仔细检查数据和签名的编码;确保这些都是您假设的base64编码,尽管这可能是正确的,因为您可以在C#中使用它.

You also should double check the encoding of data and signature; make sure that these are base64 encoded as you assume, although this is probably correct since you have it working in C#.

存在其他选项:

  1. 使用良好的旧pyOpenSSL-请参见模块 OpenSSL.crypto :

import OpenSSL

cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
                                       open('certificate.cer').read())
try:
    OpenSSL.crypto.verify(cert, signature, data, 'sha256')
    print "Signature verified OK"
except Exception as e:
    print "Signature verification failed: {}".format(e)

  • 使用 M2Crypto (不支持Python 3 ):

  • Use M2Crypto (Python 3 not supported):

    import M2Crypto
    
    cert = M2Crypto.X509.load_cert('certificate.cer', M2Crypto.X509.FORMAT_DER)
    pubkey = cert.get_pubkey()
    pubkey.reset_context('sha256')
    pubkey.verify_init()
    pubkey.verify_update(content)
    verified = pubkey.verify_final(signature)
    

  • 这篇关于Python:使用.Cer文件打开以获取公钥,然后执行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆