5

I'm using PHP's OpenSSL module for asymmetric encryption; openssl_pkey_new(), openssl_pkey_export(), and openssl_pkey_get_details() to create the keypair, and openssl_public_encrypt and openssl_private_decrypt() to encrypt and decrypt data.

How can I change the passphrase associated with the private key? Is this possible with the OpenSSL module, or do I have to create a new keypair? That would be extremely inconvenient and require the server to re-encrypt potentially thousands of files on a regular Basis.

Thanks!

4

2 回答 2

6

我需要为我在晚上构建的一个小项目执行此操作。

我们知道以下创建了一个的密钥对(公共/私有):

function newPair (&$private, &$public, $passphrase=null) {
    $res = openssl_pkey_new ();
    if ($res === false) {
        throw new Exception ("Key generation failed: ".openssl_error_string ());
        return false;
    }
    // Sets private by reference
    if (openssl_pkey_export ($res, $private, $passphrase) === false) {
        throw new Exception ("Private key export failed: ".openssl_error_string ());
        return false;
    }
    // Array returns, contains "key" element.
    $public = openssl_pkey_get_details($res);
    if ($public === false) {
        throw new Exception (openssl_error_string ());
        return false;
    }
    $public = $public["key"];
    return true;
}

open_ssl_pkey_export() 具有密码短语的魔力。所以我们可以这样更改密码:

function changePassphrase ($private, $old, $new=null) {
    $res = openssl_pkey_get_private ($private, $old);
    if ($res === false) {
        throw new Exception ("Loading private key failed: ".openssl_error_string ());
        return false;
    }
    if (openssl_pkey_export ($res, $result, $new) === false) {
        throw new Exception ("Passphrase change failed: ".openssl_error_string ());
        return false;
    }
    return $result;
}

我希望你能关注我们在这里所做的事情......!(显然异常抛出是完全可选的......我刚刚从我的代码库中逐字提取代码。)

changePassphrase() 将私钥作为字符串,以及当前和新的密码短语。我们使用 openssl_pkey_get_private() 来检索私钥的句柄,用旧密码解锁它。

(值得注意的是,密码短语实际上是用来加密私钥的,这听起来可能有点双荷兰语![Encrypting the encryption key ... ?!] openssl_pkey_get_private() 如果无法解释密钥,则返回 FALSE - 即如果密码错误,并且私钥解密为无效值。有意义吗?)

使用旧密码解锁私钥后,我们获取 OpenSSL 密钥句柄并将其传递给 openssl_pkey_export() - 就像我们在首先创建它之后所做的那样(通过 openssl_pkey_new())提供新密码......嘿- 转瞬即逝。

我希望我的代码示例读起来干净利落,我尝试以一种易于理解和遵循的方式编写它,没有不必要的“压缩”和捷径。

祝你好运!

于 2013-03-10T20:54:56.833 回答
0

使用phpseclib,一个纯 PHP RSA 实现

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

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

$rsa->setPassword('new_password');
$privatekey = $rsa->getPrivateKey();
$publickey = $rsa->getPublicKey();
?>
于 2012-12-04T21:37:15.733 回答