如何从EncryptedKey对象访问加密的AES密钥数据?Python

2024-03-28 21:56:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从EncryptedKey对象访问密钥数据字节。我不清楚这是PyAsn1对象还是Python对象还是Python加密对象。如何访问关键数据?我试过了

encryptedsessionkey=*content2['recipientInfos'][0]['encryptedKey']

以及

encryptedsessionkey=content2['recipientInfos'][0]['encryptedKey'][0:257]

我还不确定是否有错误:TypeError: initializer for ctype 'unsigned char *' must be a cdata pointer, not EncryptedKey 可能是由于一个填充问题,因为我不知道什么类型的填充被用来RSA加密AES密钥。你知道吗

    with open(outfilename, "rb") as outfilename:
          outfileread=outfilename.read()
     #this next line decodes der-encoded file into a pyasn1 object (uses pyasn1 package)
          content, rest= decode(outfileread, asn1Spec=rfc2315.ContentInfo())
          content2, rest=decode(content['content'],  asn1Spec=rfc2315.EnvelopedData())
     #this next line is a command to decrypt the encrypted AES session key file with the private key.

      lenencryptedkey=len(content2['recipientInfos'][0]['encryptedKey'])
      print(lenencryptedkey)
      encryptedsessionkey=content2['recipientInfos'][0]['encryptedKey']
      from cryptography.hazmat.primitives.asymmetric import padding      
      decryptedsessionkey=private_key.decrypt(encryptedsessionkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(), label=None))

此代码产生以下结果:

9jòÓ¡ì©V!&,ýVü^4,u* ÝU#Èñ!ÖSÇ!Á×맡žøîÔ(ÚtŦ7Öº~k¤(e@ìlµ¦ê6ÀªôK0UýÛßäTrªª¦gÿ[¬>á\÷½L­MPSA0HÈ/)Ïqü¹9Ì¿~¼_W6
ÃÅ)ßÉIPҪسÌPQ<íñ.=Í;«:A· Û_yÊJR²7XþÁò
b}T}VðµÏ*!qßbµæ$sìádØri?þÂÛû~[¡ú¶#µ    F
256
Traceback (most recent call last):
  File "C:/Users/VoxaiLap10/Desktop/pythonbible/cryptotestpemmp3_b_md5_7-19-18b.py", line 91, in <module>
    decryptedsessionkey=private_key.decrypt(encryptedsessionkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(), label=None))
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\cryptography\hazmat\backends\openssl\rsa.py", line 356, in decrypt
    return _enc_dec_rsa(self._backend, self, ciphertext, padding)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\cryptography\hazmat\backends\openssl\rsa.py", line 68, in _enc_dec_rsa
    return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\cryptography\hazmat\backends\openssl\rsa.py", line 123, in _enc_dec_rsa_pkey_ctx
    res = crypt(pkey_ctx, buf, outlen, data, len(data))
TypeError: initializer for ctype 'unsigned char *' must be a cdata pointer, not EncryptedKey

Tags: 对象keylinersaalgorithmcryptographypaddingsha256