如何使用PHP更改私钥的密码短语';什么是OpenSSL模块?

如何使用PHP更改私钥的密码短语';什么是OpenSSL模块?,php,encryption,openssl,public-key-encryption,encryption-asymmetric,Php,Encryption,Openssl,Public Key Encryption,Encryption Asymmetric,我使用PHP的OpenSSL模块进行非对称加密;openssl_pkey_new()、openssl_pkey_export()和openssl_pkey_get_details()创建密钥对,openssl_public_encrypt和openssl_private_decrypt()加密和解密数据 如何更改与私钥关联的密码短语?这在OpenSSL模块中是可能的,还是我必须创建一个新的密钥对?这将非常不方便,需要服务器定期重新加密数千个文件 谢谢 使用: 我需要为一个晚上一直在做的小项目做这

我使用PHP的OpenSSL模块进行非对称加密;openssl_pkey_new()、openssl_pkey_export()和openssl_pkey_get_details()创建密钥对,openssl_public_encrypt和openssl_private_decrypt()加密和解密数据

如何更改与私钥关联的密码短语?这在OpenSSL模块中是可能的,还是我必须创建一个新的密钥对?这将非常不方便,需要服务器定期重新加密数千个文件

谢谢

使用:


我需要为一个晚上一直在做的小项目做这件事

我们知道,以下操作将创建一个新的密钥对(公共/私有):

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()来检索私钥的句柄,并使用旧的密码短语将其解锁

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

使用旧密码短语解锁私钥后,我们获取OpenSSL密钥句柄并将其传递给OpenSSL_pkey_export()-就像我们在第一次创建私钥(通过OpenSSL_pkey_new())后提供新密码短语时所做的那样。。。嘿,普雷斯托

我希望我的代码示例读起来清晰,我已经尝试过以一种易于理解和遵循的方式编写它,而不需要不必要的“压缩”和缩短


祝你好运

我已经连续几天在OpenSSL邮件列表和Freenode的###PHP频道上询问过,但都没有结果。我在这里问的是错误的问题,还是在这种情况下,如果不通过PHP的system()函数直接调用OpenSSL,就无法更改密码短语?您绝对没有问错问题!这是一个很好的问题,我有点震惊,没有人已经回答了(直接使用PHP的OpenSSL绑定)。我希望我的回答能为你澄清一切!
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;
}
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;
}