【发布时间】:2015-07-18 01:57:24
【问题描述】:
我正在尝试将Google API with a oAuth service account 与 Python 3.4 一起使用。其中一个步骤是generate a JSON Web Token,为此我使用PyJWT。
我的生成代码如下:
# opening the certificate downloaded from the Google API console
# it is password protected by the standard password ('notasecret')
p12 = OpenSSL.crypto.load_pkcs12(open('certfromgoogle.p12', 'rb').read(), 'notasecret')
# extracting the private key from the certificate and dumping it to a PEM
# format (FILETYPE_PEM)
private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey())
# at that stage, private_key contains the private key as
# b'-----BEGIN PRIVATE KEY-----\nMIICdg(...)FIyw==\n-----END PRIVATE KEY-----\n'
# trying to get the JWT
encoded = jwt.encode(claim, private_key, algorithm='RS256', headers={"alg": "RS256", "typ": "JWT"})
对jwt.encode 的调用因TypeError: Expecting a PEM-formatted key 而崩溃。完整的追溯:
Traceback (most recent call last):
File "C:/Users/w_000/PycharmProjects/syncmagazines/testcrypto.py", line 20, in <module>
encoded = jwt.encode(claim, private_key, algorithm='RS256', headers={"alg": "RS256", "typ": "JWT"})
File "C:\Python34\lib\site-packages\jwt\api.py", line 118, in encode
key = alg_obj.prepare_key(key)
File "C:\Python34\lib\site-packages\jwt\algorithms.py", line 170, in prepare_key
raise TypeError('Expecting a PEM-formatted key.')
TypeError: Expecting a PEM-formatted key.
但是,私钥似乎已正确提取。
为什么这种格式不正确?
【问题讨论】:
-
“对 jwt.encode 的调用崩溃...” - 私钥是否加密?
-
您使用的是哪个版本的 Python?你能包括回溯吗?
-
@jww:我更新了我的代码以明确它可以以纯文本形式使用
-
@frasertweedale:Pythin 3.4,我用回溯和其他细节重写了我的问题
标签: python openssl public-key-encryption jwt