Skip to main content
 首页 » 编程设计

python之PEM 格式的私钥有什么特别之处

2025年05月04日9EasonJim

我正在尝试使用 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. 

然而,私钥似乎已正确提取。

为什么这个格式不正确?

请您参考如下方法:

检查了 PyJWT 源代码后,很明显该库希望 PEM 数据为字符串类型,但您提供的是一个字节串(在您的问题中通过 b'...' 文字显而易见)。 有问题的函数是 prepare_key , 以及 acceptable string types 的定义.

您必须将私钥数据解码为 native str输入:

private_key_bytes = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()) 
private_key = private_key_bytes.decode('utf-8') 

这似乎只适用于 Python 3,但上面的代码也适用于 Python 2。