Voting

: nine minus nine?
(Example: nine)

The Note You're Voting On

Senthryl
15 years ago
This function can be used to create a private key for use by JCE in Java. For example, a private key could be generated by a PHP script and the result could be used in a Java client application.

Java requires the private key in DER format with some extra ASN.1 wrapping. The function below can be used to convert the output of openssl_pkey_export into a format suitable for input into JCE:

<?php
function derLength($length) {
if (
$length < 128) return str_pad(dechex($length), 2, '0', STR_PAD_LEFT);
$output = dechex($length);
if (
strlen($output) % 2 != 0) $output = '0'.$output;
return
dechex(128 + strlen($output)/2) . $output;
}
function
convertPemToDer($pem) {
$matches = array();
if (!
preg_match('~^-----BEGIN ([A-Z ]+)-----\s*?([A-Za-z0-9+=/\r\n]+)\s*?-----END \1-----\s*$~D', $pem, $matches)) {
die(
'Invalid PEM format encountered.'."\n");
}
$derData = base64_decode(str_replace(array("\r", "\n"), array('', ''), $matches[2]));
$derData = pack('H*', '020100300d06092a864886f70d010101050004'.derLength(strlen($derData))) . $derData;
$derData = pack('H*', '30'.derLength(strlen($derData))) . $derData;
return
$derData;
}
?>

Example use:
<?php
$keys
= openssl_pkey_new(array('digest_alg' => 'sha1', 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 2048));
if (
$keys === false) die('Failed to generate key pair.'."\n");
if (!
openssl_pkey_export($keys, $privateKey)) die('Failed to retrieve private key.'."\n");
$javaKey = convertPemToDer($privateKey);

file_put_contents('key_for_java.der', $javaKey);
?>

Exporting a public key for use with JCE is trickier, since the Java libraries require the key to be input as a byte array. In effect, the public key outputted by openssl_pkey_get_details() must be base64 decoded as above, and then parsed as ASN.1 to receive the actual key bytes (this can be done either on the PHP side or the Java side).

The following link is an invaluable resource to understanding the output from these functions:
"A Layman's Guide to a Subset of ASN.1, BER, and DER"
http://luca.ntop.org/Teaching/Appunti/asn1.html

<< Back to user notes page

To Top