I have two XML files, structured as follows:
My Key
<RSAKeyValue>
<Modulus> ... </Modulus>
<Exponent> ... </Exponent>
<P> ... </P>
<Q> ... </Q>
<DP> ... </DP>
<DQ> ... </DQ>
<InverseQ> ... </InverseQ>
<D> ... </D>
</RSAKeyValue>
A Public Key
<RSAKeyValue>
<Modulus> ... </Modulus>
<Exponent> ... </Exponent>
</RSAKeyValue>
I am using the xmlseclibs
library by Robert Richards which requires a .PEM representation of the key in order to encrypt and decrypt things.
As an encryption novice, I'm not sure where to begin, and a cursory Google search did not reveal anything particularly obvious...
Thanks!
PEM encoded RSA private key is a format that stores an RSA private key, for use with cryptographic systems such as SSL. A public key can be derived from the private key, and the public key may be associated with one or more certificate files.
For those who want the resulting PEM to be readable by BouncyCastle:
The final solution I am happy with:
java XMLSec2PEM my.xml > my.pem
my.pem
manually a bitorg.bouncycastle.openssl.PEMReader.readObject()
returns null
:-(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
my.pkcs8.pem
is readable with the PEMReader
my solution in python works like this:
xml = etree.fromstring(key_bin)
modulus = xml.find('Modulus').text
exponent = xml.find('Exponent').text
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])
exp_num = int(exp, 16)
mod_num = int(mod, 16)
rsa_key = rsa.PublicKey(mod_num, exp_num)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With