Convert pem rsa key to xml for C # RSACryptoServiceProvider.FromXmlString

I am creating an RSA public and private key with PHP:

function genKeys($pkey, $skey)
{
    $pkGenerate = openssl_pkey_new(array(
        'private_key_bits' => 2048,
        'private_key_type' => OPENSSL_KEYTYPE_RSA
    ));

    $pkGeneratePrivate = null;
    openssl_pkey_export($pkGenerate, $pkGeneratePrivate);

    $pkGenerateDetails = openssl_pkey_get_details($pkGenerate);
    $pkGeneratePublic  = $pkGenerateDetails['key'];

    openssl_pkey_free($pkGenerate);

    $pkImport        = openssl_pkey_get_private($pkGeneratePrivate);
    $pkImportDetails = openssl_pkey_get_details($pkImport);
    $pkImportPublic  = $pkImportDetails['key'];

    openssl_pkey_free($pkImport);

    $result = (bool) strcmp($pkGeneratePublic, $pkImportPublic);

    if ($result) {
        file_put_contents($pkey, $pkGeneratePrivate);
        file_put_contents($skey, $pkGeneratePublic);
    }

    return $result;

}

      

And I need a PEM file with RSACryptoServiceProvider.

So how to convert PEM public and private to XML?

+3


source to share


2 answers


Using http://phpseclib.sourceforge.net/ :



<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('...');

echo $rsa->getPrivateKey(CRYPT_RSA_PRIVATE_FORMAT_XML);

      

+2


source


This answer is a bit late, I had problems to figure out what you are looking for exactly and can decipher it now.

The .Net in RSACryptoServiceProvider.FromXmlString uses an XML key format similar to that of XKMS 2.0 , only with a different document element.

The openssl extension in PHP does not offer a function to create it directly, however with openssl_pkey_get_details()

function
you can get all the RSA key details you need to create an XML file. Then it's pretty straight forward:

$rsa = openssl_pkey_get_details($pkGenerate)['rsa'];

$xml = new SimpleXMLElement("<RSAKeyValue/>"); // Use <RSAKeyPair/> for XKMS 2.0

// .Net / XKMS openssl RSA indecies to XML element names mappings
$map = ["n"    => "Modulus", "e"    => "Exponent", "p"    => "P",        "q"    => "Q",
        "dmp1" => "DP",      "dmq1" => "DQ",       "iqmp" => "InverseQ", "d"    => "D",];

foreach ($map as $key => $element) {
    $xml->addChild($element, base64_encode($rsa[$key]));
}

$xml->asXML('php://output');

      

This example continues after generating a key where you have a resource in a variable $pkGenerate

and "saves" it to stdout (for demonstration purposes). You can also save it to a file:

$xml->asXML('/path/to/file');

      



or assigning to a variable:

$xmlString = $xml->asXML();

      

So, technically, if you are using the openssl extension, you don't need to add the complete phpseclib just to generate the XML.

Related material:

+2


source







All Articles