How convert RSA public key, from XML to PEM (PHP)?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Illegal to have multiple roots (start tag in epilo
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
we know
X.509
XML_Signature
so we end up with
if your xml-file isn't a XML_Signature
I'm assuming that by XML format, you mean XML DSig RSAKeyValue, and that by PEM format you mean what OpenSSL exports in between
-----BEGIN PUBLIC KEY-----
and-----END PUBLIC KEY-----
.You need first to extract the modulus and public exponent from the XML.
You can easily convert these into a bit string using
base64_decode
.Once this is done, you need to build the ASN.1 public key structure somehow.
What OpenSSL exports between BEGIN/END PUBLIC KEY is an X.509 SubjectPublicKeyInfo structure.
The
subjectPublicKey
is made of a sequnce is described in the PKCS#1 spec:The
algorithm
(anAlgorithmIdentifier
) is also described in the PKCS#1 spec (see section A.1):This structure needs to be serialized in DER form, then base64-encoded and then placed between the BEGIN/END delimiters.
I don't know of any PHP library to do the ASN.1/DER encoding unfortunately (the rest is relatively easy, but dealing with ASN.1 tends to be tedious).
The PHP/PEAR Crypt_RSA module can construct RSA public keys from modulus and exponent, but its
toString()
method uses a custom format (just the base64-encoding of the result of PHPserialize
on the array structure, which has nothing to do with the ASN.1/DER encoding).There is no standard for storing RSA public keys in XML. So the manner of conversion will depend on the XML you have.
Here's an example of how to read XML RSA keys in PHP:
Maybe you should have a look here
Extract the two base64-encoded strings, convert and pass to PEAR::Crypt_RSA, then export as text file, then openssl convert?
Check this too
Just for completeness, here is a working example of creating the PEM from modulus in python. You could call it in a subprocess from PHP if necessary.
The meat of the solution is:
Where
E_PREFIX
andN_PREFIX
are constants that (as far as I can tell) depend on the exponent and key length. Here is a quick table I have constructed:If someone knows a more general way to compute the prefixes, do tell.