我想在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