对于我正在进行的一个项目,我正在使用Amazon AWS SDK For PHP,并且我需要以纯文本格式检索服务器环境的密码。然而,ec2方法的文档证实了我们的发现:该方法只会返回一个加密的字符串。从表面上看,这很好,因为AWSSDKforPHP使用未加密的HTTPPOST请求通过cURL发送和接收数据,对用户来说是无形的。因此,我们的密码数据不会只是在网络上传播。
问题是没有任何解释如何解密字符串。我把私钥作为PEM文件,但没有任何方法或文档可以说明如何处理该字符串以使其可用。几次尝试都没有结果,我开始认为我需要重新思考我正在进行的项目的策略,但后来我找到了AWS SDK for PHP的最后一个版本的代码,它揭示了如何解密字符串以生成纯文本形式的密码。
我发现的答案是getPasswordData方法返回一个字符串,该字符串是base64编码和加密的。在使用PHP的OpenSSL库成功解密之前,您需要使用base64_decode()对其进行解码。以下功能兼顾两者:
/**
* @param obj $ec2_client The EC2 PHP client, from the AWS SDK for PHP
* @param string $client_id The ID of the client whose password we're trying to get.
* @return mixed The unencrypted password for the client, or false on failure.
*/
function aws_get_ec2_password($ec2_client, $client_id){
// First, run getPasswordData to get the Password Data Object.
$pw_obj = $ec2_client->getPasswordData($client_id);
// Next, use the local get() method to isolate the password
$pw_b64 = $pw_obj->get("PasswordData");
// Decode the password string.
$pw_encrypted = base64_decode($pw_b64);
// Now, get your PEM key.
//
// You can also use a raw string of the PEM key instead of get_file_contents(),
// or adjust the function so that you can pass it as an argument.
//
// Technically, this step might not be necessary, as the documentation for
// openssl_private_decrypt() suggests that $key can just be the path, and it will
// create the key object internally.
$key = openssl_get_privatekey(file_get_contents("path/to/key.pem"));
// Create an empty string to hold the password.
$pw = "";
// Finally, decrypt the string and return (will return false if decryption fails).
if(openssl_private_decrypt($pw_encrypted, $pw, $key)){
return $pw;
}else{
return false;
}
}
我希望这能帮助其他人避免它给我带来的头痛!