Sam*_*uke 5 php encryption openssl encryption-asymmetric public-key-encryption
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我希望你能按照我们在这里所做的一切......!(显然异常抛出纯粹是可选的......我只是从代码库中逐字地提取代码.)
changePassphrase()将私钥作为字符串,以及当前和新的密码.我们使用openssl_pkey_get_private()来检索私钥的句柄,使用旧的密码解锁它.
(值得注意的是,密码短语实际上用于加密私钥,这可能听起来有点双重![加密加密密钥......?!] openssl_pkey_get_private()如果无法解释密钥则返回FALSE - 即如果密码错误,私钥解密为无效值.有意义吗?)
使用旧密码解锁私钥后,我们使用OpenSSL密钥句柄并将其传递给openssl_pkey_export() - 就像我们在首先创建它(通过openssl_pkey_new())后提供新密码一样......并且嘿-presto.
我希望我的代码示例干净利落地阅读,我试图以一种易于理解和遵循的方式编写它,没有不必要的"压缩"和短切.
祝好运!
<?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();
?>
Run Code Online (Sandbox Code Playgroud)