How do I convert an XML RSA key to a PEM file?
For those who want the resulting PEM to be readable by BouncyCastle:
- use XMLSec2PEM tool to get a pem file
- convert pem to pkcs8 and back (!)
The final solution I am happy with:
java XMLSec2PEM my.xml > my.pem
- edit
my.pem
manually a bit org.bouncycastle.openssl.PEMReader.readObject()
returnsnull
:-(openssl pkcs8 -topk8 -inform pem -in my.pem -outform pem -nocrypt -out my.pkcs8
openssl pkcs8 -inform pem -nocrypt -in my.pkcs8 -out my.pkcs8.pem
- now
my.pkcs8.pem
is readable with thePEMReader
my solution in python works like this:
- extract modulus and exponent from xml
xml = etree.fromstring(key_bin) modulus = xml.find('Modulus').text exponent = xml.find('Exponent').text
- decode them in base64 and iterate the result to save it as a
character string of length 2:
mod_b64 = b64decode(modulus.encode()) exp_b64 = b64decode(exponent.encode()) exp = ''.join(['{:02x}'.format(x) for x in exp_b64]) mod = ''.join(['{:02x}'.format(x) for x in mod_b64])
- Convert the hexadecimal string to integer and generate the rsa
public key with the rsa library:
exp_num = int(exp, 16) mod_num = int(mod, 16) rsa_key = rsa.PublicKey(mod_num, exp_num)
- Finally any text can be encrypted:
msg_cryp = rsa.encrypt(msg.encode('ascii'), rsa_key) msg_cryp_str = b64encode(msg_cryp).decode('ascii')
I did this development to consume a web service which requires that an encrypted password be sent from a public key in XML format. In this way I managed to encrypt the password and consume the web service without problems.
I have found a Java utility that can do it.