【问题标题】:Supplied key param cannot be coerced into a private key with Google APIs提供的密钥参数不能通过 Google API 强制转换为私钥
【发布时间】:2014-02-04 14:48:48
【问题描述】:

我正在尝试测试我找到的 here 这个示例,以便我可以在客户端直接上传,而无需用户使用 Google Cloud Storage 登录。

所有表达的常量都有正确的值,路径正确且内容不为空。

我得到的错误:

openssl_sign(): supplied key param cannot be coerced into a private key

我实现的功能是:

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);
    }

【问题讨论】:

    标签: php google-cloud-storage php-openssl


    【解决方案1】:

    更安全的方法是使用Google API PHP client 附带的Google_Signer_P12 类来执行此操作。

    代码示例:

    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);
    

    【讨论】:

    • google_signer_p12 在新版本中被移除了,改用什么?
    【解决方案2】:

    首先,您需要使用openssl_pkcs12_read 来读取密钥文件,而不是file_get_contents。其次,我相信你想把第二个参数留给openssl_get_privatekey

    我强烈建议您为此使用google-api-php-client,其中有Google_P12Signer.php

    【讨论】:

    • 所以我可以使用这个来生成 URL?
    • 什么是“这个”?如果您的意思是 google-api-php-client,那么是的
    • 哦...您在哪里可以找到 api-library 的文档?
    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 2023-03-16
    • 2021-03-01
    • 2014-12-11
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多