虽然这个问题之前已经被问过并在(JWT encrypting payload in python? (JWE))中被问过,但我似乎无法让 JWK 工作——我尝试导入我的纯文本 RSA 密钥并得到一个错误(在下面添加堆栈跟踪)。谁能告诉我我做错了什么?
Traceback (most recent call last):
File "statenc.py", line 169, in <module>
test()
File "statenc.py", line 155, in test
keypair = statEnc()
File "statenc.py", line 48, in __init__
self.pub_jwk = jwk.JWK.import_from_pem(self, data=self.pubkeystr, password=None)
File "/usr/lib/python3.6/site-packages/jwcrypto/jwk.py", line 624, in import_from_pem
data, password=password, backend=default_backend())
File "/usr/lib/python3.6/site-packages/cryptography/hazmat/primitives/serialization.py", line 20, in load_pem_private_key
return backend.load_pem_private_key(data, password)
File "/usr/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 978, in load_pem_private_key
password,
File "/usr/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1129, in _load_key
mem_bio = self._bytes_to_bio(data)
File "/usr/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 432, in _bytes_to_bio
data_char_p = self._ffi.new("char[]", data)
TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str
我的代码如下:(如果没有提供现有密钥,这是用于初始化新 RSA 密钥的模块)
def __init__(self, pubkeystr = None, privkeystr = None, sessionkey = None):
self.pubkeystr = pubkeystr
self.privkeystr = privkeystr
self.sessionkey = sessionkey
if pubkeystr == None or privkeystr == None: #if blank, generate keys
self.random_generator = Random.new().read
self.keys = RSA.generate(1024, self.random_generator)
self.pubkey = self.keys.publickey()
self.pubkeystr = self.pubkey.exportKey(format='PEM',
passphrase=None,
pkcs=1).decode('utf-8')
self.pubcipher = PKCS1_OAEP.new(self.pubkey)
self.privcipher = PKCS1_OAEP.new(self.keys)
self.privkeystr = self.keys.exportKey(format='PEM',
passphrase=None,
pkcs=1).decode('utf-8')
self.privkey = self.keys.exportKey()
else: #import the keys
self.pubkeystr = pubkeystr
self.privkeystr = privkeystr
self.pubkey = RSA.importKey(pubkeystr)
self.pubcipher = PKCS1_OAEP.new(self.pubkey)
self.privkey = RSA.importKey(privkeystr)
self.privcipher = PKCS1_OAEP.new(self.privkey)
if sessionkey == None:
sessionkey = get_random_bytes(16)
else:
self.sessionkey = sessionkey
# Now setup the JWKs
self.pub_jwk = jwk.JWK.import_from_pem(self, data=self.pubkeystr, password=None)
self.priv_jwk = jwk.JWK.import_from_pem(self, data=self.privkeystr, password=None)
print("%s \n %s" % (self.pub_jwk, self.priv_jwk))