How do I get access to RSA-encrypted AES key data from EncryptedKey object? Python

253 views Asked by At

I am trying to access key data bytes from an EncryptedKey object. I am unclear on whether this is a PyAsn1 object or a Python object or a Python cryptography object. How do I access the key data? I have tried

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

as well as

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

I am additionally unsure if error: TypeError: initializer for ctype 'unsigned char *' must be a cdata pointer, not EncryptedKey could be due to a padding issue, as I do not know what type of padding was used to RSA encrypt the AES key.

    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))

this code results in the following:

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
0

There are 0 answers