问题
I have pub key in xml format:
<RSAKeyValue><Modulus>xF9y25EXh8n99sXtU/JAsYTwML6PB7gSCE8tWw8Www2KBfDqohQBL8FMs8jzsDQa7WwoEmiVJ1resEC9YXJGbwQyWgb9qgooC9oSnCB/TkRdBybwby0DKuZOzq+609OBGkwWpgnS4QVCBc6eW+10l3qE3/2hKdcSV+08iRYp7zs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
So i try thms like this:
from M2Crypto import RSA
from xml.dom.minidom import parseString
import base64
dom = parseString(pubKey)
e = base64.b64decode(dom.getElementsByTagName('Exponent')[0].childNodes[0].data)
n = base64.b64decode(dom.getElementsByTagName('Modulus')[0].childNodes[0].data)
rsa = RSA.new_pub_key((e, n))
Got error:
...
rsa = RSA.new_pub_key((e, n))
File "/usr/lib/pymodules/python2.6/M2Crypto/RSA.py", line 390, in new_pub_key
m2.rsa_set_e(rsa, e)
M2Crypto.RSA.RSAError: invalid length
Any ideas?
回答1:
The RSA.new_pub_key documentation states that e
and n
need to be in OpenSSL MPINT format (4-byte big-endian bit-count followed by the appropriate number of bits). It seems like at least your e
is not in that format. If you take a look at test_rsa.py, you can see comments that say:
'\000\000\000\003\001\000\001' # aka 65537 aka 0xf4
It seems your e
is just '\001\000\001'. If we prepend the '\000\000\000\003' to it, your sample app gets a bit further along, but then fails trying to set n
. I haven't looked into how to create valid OpenSSL MPINT values, so this isn't a complete answer to your question.
回答2:
I read M2Crypto source,find have m2
PyObject.
//I think these is hex.
e = base64.b64decode(dom.getElementsByTagName('Exponent')[0].childNodes[0].data)
n = base64.b64decode(dom.getElementsByTagName('Modulus')[0].childNodes[0].data)
change hex to mpi
from M2Crypto import m2
bnE=m2.hex_to_bn(e)
bnN=m2.hex_to_bn(n)
e=m2.bn_to_mpi(bnE)
n=m2.bn_to_mpi(bnN)
done!
rsa = RSA.new_pub_key((e, n))
回答3:
I know this is an ancient question, but it still shows up highly in searches on this topic so I'm adding my two cents. I needed exactly this functionality for the PyVEP project and you can find the function I wrote here: https://github.com/mozilla/PyVEP/blob/master/vep/jwt.py#L242
来源:https://stackoverflow.com/questions/1900083/gen-public-key-from-xml-data-file-using-m2crypto-for-signature-verification