2013-12-10 35 views
0

我嘗試使用方法產生谷歌雲存儲對象標識的URL是使用OpenSSL如何使用PHP

$fp = fopen($key, 'r'); //open the PEM file 
$priv_key = fread($fp,8192); 
fclose($fp); 
$pkeyid = openssl_get_privatekey($priv_key,"password"); 

openssl_sign($response["data_to_sign"], $signature, $pkeyid,'sha256'); 

$sign = base64_encode($signature) 

這是正確的方法來爲谷歌簽署的網址生成簽名?

回答

1

這裏有使用PHP簽署了谷歌雲存儲URL的例子: https://groups.google.com/forum/#!msg/google-api-php-client/jaRYDWdpteQ/xbNTLfDhUggJ

但是 - 我注意到這是標籤與谷歌應用程序引擎......如果你的代碼是谷歌應用程序引擎的內部運行,您應該使用內置的應用程序標識服務 - (注意,只有在應用程序在生產環境中部署,而不是在本地運行時才能使用) - 這意味着您無需下載或處理任何私鑰:

require_once 'google/appengine/api/app_identity/AppIdentityService.php'; 

$sign_result = AppIdentityService::signForApp($message); 

您需要確保服務ac與App Engine應用程序關聯的計數已添加到擁有Cloud Storage存儲桶的項目的團隊。

+0

什麼是不使用谷歌應用程序引擎的方法? – RyanDawkins

+0

使用下載的私鑰創建服務帳戶(請參閱https://developers.google.com/accounts/docs/OAuth2ServiceAccount)。該私鑰可用於以相同的方式簽署數據。上面的Google Group論壇鏈接顯示瞭如何使用openssl_sign完成此操作。 http://www.php.net/manual/en/function.openssl-sign.php顯示瞭如何讀取私鑰文件的例子。 – aeijdenberg

+0

關於它所說的部分,「*簽名將會在這裏*」這是什麼意思?我指的是你用openssl_sign給出的例子。 (關於這個例子,我最困惑的是你應該插入哪些信息) – RyanDawkins

0

有一點要注意,我花了大約兩個小時:谷歌在雲端控制檯的「證書」部分中

的GoogleAccessId你傳遞到該URL的電子郵件地址。這不是谷歌在其文檔中建議的替換字符串的OAuth客戶端ID。

1

我把所有的答案放在一起。這應該在開箱即用的項目中起作用。如果路徑中有空間,則需要rawurlencode個別組件,而不是urlencode

function signedGoogleStorageURL($bucketName, $resourcePath, $duration = 10, $method = 'GET') 
{ 
    $expires = time() + $duration; 
    $content_type = ($method == 'PUT') ? 'application/x-www-form- 
    urlencoded' : ''; 
    $to_sign = ($method . "\n" . 
       /* Content-MD5 */ "\n" . 
       $content_type . "\n" . 
       $expires . "\n" . 
       "/" . $bucketName . $resourcePath); 

    $sign_result = AppIdentityService::signForApp($to_sign); 
    $signature = urlencode(base64_encode($sign_result['signature'])); 
    $email = AppIdentityService::getServiceAccountName(); 

    return ('https://storage.googleapis.com/' . $bucketName . 
      $resourcePath . 
      '?GoogleAccessId=' . $email . 
      '&Expires=' . $expires . 
      '&Signature=' . $signature); 
} 

$signedPath = signedGoogleStorageURL(AppIdentityService::getDefaultVersionHostname(), "/my_folder/my_file", 60);