我还没有找到一种方法从PEM文件加载RSA私钥以在python-crypto(签名)中使用它.
python-openssl可以加载PEM文件,但是PKey对象不能用于检索与Crypto.PublicKey.construct()一起使用的密钥信息(p,q,...).
我推荐使用M2Crypto而不是python-crypto.无论如何,您将需要M2Crypto来解析PEM,其EVP api可以根据特定算法释放您的代码.
private = """ -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMPFZQ7Ic+BmmeWHvvVP4Yj yu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQJAIHCz8h37N4ScZHThYJgt oIYHKpZsg/oIyRaKw54GKxZq5f7YivcWoZ8j7IQ65lHVH3gmaqKOvqdAVVt5imKZ KQIhAPPsr9i3FxU+Mac0pvQKhFVJUzAFfKiG3ulVUdHgAaw/AiEA3ozHKzfZWKxH gs8v8ZQ/FnfI7DwYYhJC0YsXb6NSvR8CIHymwLo73mTxsogjBQqDcVrwLL3GoAyz V6jf+/8HvXMbAiEAj1b3FVQEboOQD6WoyJ1mQO9n/xf50HjYhqRitOnp6ZsCIQDS AvkvYKc6LG8IANmVv93g1dyKZvU/OQkAZepqHZB2MQ== -----END RSA PRIVATE KEY----- """ message = "python-crypto sucks" # Grab RSA parameters e, n from M2Crypto import RSA, BIO bio = BIO.MemoryBuffer(private) rsa = RSA.load_key_bio(bio) n, e = rsa.n, rsa.e # In Python-crypto: import Crypto.PublicKey.RSA pycrypto_key = Crypto.PublicKey.RSA.construct((n, e)) # Use EVP api to sign message from M2Crypto import EVP key = EVP.load_key_string(private) # if you need a different digest than the default 'sha1': key.reset_context(md='sha256') key.sign_init() key.sign_update(message) signature = key.sign_final() # Use EVP api to verify signature public = """ -----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMP FZQ7Ic+BmmeWHvvVP4Yjyu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQ== -----END PUBLIC KEY----- """ from M2Crypto import BIO, RSA, EVP bio = BIO.MemoryBuffer(public) rsa = RSA.load_pub_key_bio(bio) pubkey = EVP.PKey() pubkey.assign_rsa(rsa) pubkey.reset_context(md="sha256") pubkey.verify_init() pubkey.verify_update(message) assert pubkey.verify_final(signature) == 1
请参阅http://svn.osafoundation.org/m2crypto/trunk/tests/test_rsa.py,但我更喜欢使用与算法无关的EVP API http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py.
如何验证Python中的RSA SHA1签名?解决了类似的问题.
这是(接近)你尝试做什么的?
public_key_filename = 'public_key.pem' rsa = M2Crypto.RSA.load_pub_key(pk)
这应该工作.问题也可能在openssl上,当你只使用openssl(不是在Python中)时它是否有效?
链接到我Too Crypto