簡體   English   中英

如何使用PHP的OpenSSL模塊更改私鑰的密碼?

[英]How to change the passphrase of a private key using PHP's OpenSSL module?

我正在使用PHP的OpenSSL模塊進行非對稱加密; openssl_pkey_new(),openssl_pkey_export()和openssl_pkey_get_details()用於創建密鑰對,openssl_public_encrypt和openssl_private_decrypt()用於加密和解密數據。

如何更改與私鑰關聯的密碼? 這可能是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;
}

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())后提供新密碼一樣......並且嘿-presto。

我希望我的代碼示例干凈利落地閱讀,我試圖以一種易於理解和遵循的方式編寫它,沒有不必要的“壓縮”和短切。

祝好運!

使用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();
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM