我想在Python 3.4中使用Google API with a oAuth service account。其中一个步骤是generate a JSON Web Token,为此我使用PyJWT
。对于PEM格式的私钥有什么特别之处?
我对代码如下:
# 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的调用崩溃...”* - 私钥是否被加密? – jww
您使用的是哪个版本的Python?你可以包括追溯? – frasertweedale
@jww:我更新了我的代码,以明确它是否可用于明文 – WoJ