如何在PHP中使用PKCS8编码私钥

时间:2014-10-14 20:18:20

标签: java php openssl rsa private-key

java中的以下代码完成了这项工作:

        InputStream is = CipherRunnable.class.getClassLoader().getResourceAsStream("privateKey.pem");
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory keyFactory;
        keyFactory = KeyFactory.getInstance("RSA");
        Key key = keyFactory.generatePrivate(privateKeySpec);

PHP中的等效代码是什么?

2 个答案:

答案 0 :(得分:2)

以下是使用phpseclib, a pure PHP RSA implementation在PHP中创建PKCS8公钥/私钥的方法:

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

$rsa = new Crypt_RSA();

$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS8);

extract($rsa->createKey());

echo $privatekey . "\r\n\r\n";
echo $publickey;

答案 1 :(得分:0)

如果你只想使用OpenSSL,似乎没有任何我能找到的PHP的PKCS8函数;无论您使用何种版本的OpenSSL,都是您获得的默认格式。

这是我最终做的事情,由this answerOpenSSL RSA Tool documentation提供。注意我正在创建全新的自签名证书/密钥,所以如果你不是,你可以跳过除最后几行之外的所有内容:

<?php
// Create the private and public key
$sslConfig = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

$privKey = openssl_pkey_new($sslConfig);

$csrConfig = array(
    "countryName" => "yourcountry",
    "stateOrProvinceName" => "yourstate",
    "localityName" => "yourcity",
    "organizationName" => "yourcompany",
    "organizationalUnitName" => "yourorg",
    "commonName" => "your.domain.name"
);

// create a certificate signing request
$csr = openssl_csr_new($csrConfig, $privKey, $sslConfig);
// self-sign for 365 days
$signed = openssl_csr_sign($csr, null, $privKey, 365, $sslConfig);

// Extract the public certificate
openssl_x509_export($signed, $sslCert);

// Extract the private key (in default openssl format, which for 1.x will be PKCS8 / "PRIVATE KEY" format)
openssl_pkey_export($privKey, $sslKey);

// Convert private key to RSA ("traditional" / "SSLeay" / "RSA PRIVATE KEY") format
exec('echo '.escapeshellarg($sslKey).' | openssl rsa -outform PEM 2>/dev/null', $output, $return_var);

$traditionalSslKey = implode("\n", $output);

var_dump($traditionalSslKey); // private key
var_dump($sslcert); // certificate (public key is available via openssl_pkey_get_public($sslcert))