php 不能使用 Google API 将提供的密钥参数强制转换为私钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21149200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Supplied key param cannot be coerced into a private key with Google APIs
提问by ryandawkins
I'm trying to test this example that I found hereso that I can do a direct upload on the client side without having the user login using Google Cloud Storage.
我正在尝试测试我在此处找到的这个示例,以便我可以在客户端直接上传,而无需用户使用 Google Cloud Storage 登录。
All of the constants expressed have their correct values, and the path is correct and does not have an empty contents.
所有表示的常量都有其正确的值,并且路径正确且没有空内容。
The error I'm getting:
我得到的错误:
openssl_sign(): supplied key param cannot be coerced into a private key
My function implemented is:
我实现的功能是:
public static function storageURL( $id, $method = 'GET', $duration = 10 ) {
$key = file_get_contents(self::KEY_FILE);
$pkey = openssl_get_privatekey($key, 'notasecret');
$expires = time( ) + $duration;
$content_type = ($method == 'PUT') ? 'application/x-www-form-urlencoded' : '';
$to_sign = ($method . "\n" .
/* Content-MD5 */ "\n" .
$content_type . "\n" .
$expires . "\n" .
'/'.self::BUCKET_NAME.'/' . $id);
$signature = '*Signature will go here*';
if (!openssl_sign( $to_sign, $signature, $pkey, 'sha256' ))
{
error_log( 'openssl_sign failed!' );
$signature = '<failed>';
} else {
$signature = urlencode( base64_encode( $signature ) );
}
return ('https://'.self::BUCKET_NAME.'.commondatastorage.googleapis.com/' .
$id .
'?GoogleAccessId=' . self::SERVICE_ACCOUNT_NAME .
'&Expires=' . $expires . '&Signature=' . $signature);
}
采纳答案by jterrace
First, you need to use openssl_pkcs12_readto read the key file, not file_get_contents. Second, I believe you want to leave off the second parameter to openssl_get_privatekey.
首先,您需要使用openssl_pkcs12_read读取密钥文件,而不是file_get_contents. 其次,我相信您想将第二个参数留给openssl_get_privatekey.
I highly recommend you use google-api-php-clientfor this, which has Google_P12Signer.php
我强烈建议您为此使用google-api-php-client,其中包含Google_P12Signer.php
回答by Muhammad Reda
The safer way is to use Google_Signer_P12class shipped with Google API PHP clientto do that.
更安全的方法是使用Google API PHP 客户端Google_Signer_P12附带的类来做到这一点。
Code sample:
代码示例:
set_include_path(get_include_path() . PATH_SEPARATOR . 'PATH/TO/API/src');
require_once 'Google/Signer/P12.php';
$p12contents = file_get_contents('FILE.p12');
$googleSigner = new Google_Signer_P12($p12contents, 'notasecret');
$signature = $googleSigner->sign($data);

