2014-07-10 40 views
0

我只是跟着https://developers.google.com/storage/docs/accesscontrol?hl=zh-TW#Signed-URLs使用gsutil生成签名的URL,它工作正常。如何使用Python在服务器端生成签名的url?

但我的问题是“如何在服务器端生成签名的url?”

以上的云存储链接中提到的示例项目https://github.com/GoogleCloudPlatform/storage-signedurls-python

是否适合在App Engine环境?如果是这样,私钥文件应该放在哪里?

还是有更好的方法来解决这个问题吗?

回答

0

如果您使用的是Python,则有一个示例Python应用程序生成名为storage-signedurls-python的已签名URL。

+0

蟒蛇样品确实在我的本地环境的工作,但在GoogleAppEngineLauncher和在线运行时,它有问题。我想这是因为启动器和在线App Engine没有“PyCrypto”和“请求”。我甚至尝试在我的项目文件夹中制作“Crypto”,但它也不起作用。 – RedBeanPieLarry

0

下面是我们如何使它工作:

步骤1:https://console.developers.google.com/ “的API &认证/证书”获取P12文件/证书

下载P12文件选项卡。

步骤2:转换P12文件DER格式

找到一台Linux计算机打开并使用连接终端 命令:

openssl pkcs12 -in <filename.p12> -nodes -nocerts > <filename.pem> 
# The current Google password for the p12 file is `notasecret` 

openssl rsa -in <filename.pem> -inform PEM -out <filename.der> -outform DER 

步骤3:将DER文件base64编码字符串

Python控制台:

private_key = open(‘<filename.der>’, 'rb').read() 
print private_key.encode('base64') 

复制并粘贴到App引擎脚本中。

步骤4:在应用服务引擎启用PyCrypto

app.yaml中必须有一个行来启用PyCrypto:

- name: pycrypto 
    version: latest 

步骤5:Python代码来创建签名URL

import Crypto.Hash.SHA256 as SHA256 
import Crypto.PublicKey.RSA as RSA 
import Crypto.Signature.PKCS1_v1_5 as PKCS1_v1_5 

der_key = “””<copy-paste-the-base64-converted-key>”””.decode('base64') 

bucket = <your cloud storage bucket name (default is same as app id)> 
filename = <path + filename> 

valid_seconds = 5 
expiration = int(time.time() + valid_seconds) 

signature_string = 'GET\n\n\n%s\n' % expiration 
signature_string += bucket + filename 



# Sign the string with the RSA key. 
signature = '' 
try: 
    start_key_time = datetime.datetime.utcnow() 
    rsa_key = RSA.importKey(der_key, passphrase='notasecret') 
    #objects['rsa_key'] = rsa_key.exportKey('PEM').encode('base64') 
    signer = PKCS1_v1_5.new(rsa_key) 
    signature_hash = SHA256.new(signature_string) 
    signature_bytes = signer.sign(signature_hash) 
    signature = signature_bytes.encode('base64') 

    objects['sig'] = signature 
except: 
    objects['PEM_error'] = traceback.format_exc() 

try: 
    # Storage 
    STORAGE_CLIENT_EMAIL = <Client Email from Credentials console: Service Account Email Address> 
    STORAGE_API_ENDPOINT = 'https://storage.googleapis.com' 

    # Set the query parameters. 
    query_params = {'GoogleAccessId': STORAGE_CLIENT_EMAIL, 
       'Expires': str(expiration), 
       'Signature': signature} 


    # This is the signed URL: 
    download_href = STORAGE_API_ENDPOINT + bucket + filename + '?' + urllib.urlencode(query_params) 

except: 
    pass 

来源

How to get the p12 file.

Signing instructions.

Inspiration for how to sign the url.

相关问题