Decrypt using RSA public key using PyCrypto

As I understand it, I should be able to use RSA to ensure authenticity or confidentiality, as I wish. In my case, I want to ensure authenticity, so I encrypt the data with the private key and let everyone decrypt it with the public key. The data is not confidential, but I have to guarantee that it was created by the owner of the public (and private) key.

When I try to decrypt using PyCrypto, I get No private key . Error from PyCrypto. The code looks like this:

def _decrypt_rsa(decrypt_key_file, cipher_text): from Crypto.PublicKey import RSA from base64 import b64decode key = open(decrypt_key_file, "r").read() rsakey = RSA.importKey(key) raw_cipher_data = b64decode(cipher_text) decrypted = rsakey.decrypt(raw_cipher_data) return decrypted 

I call it along the path to the public key file (in OpenSSH format.) The encrypted data is not generated by me, and this was not done with Python, but PHP. PHP has an openssl_public_decrypt function that easily decrypts this data.

Is it possible to decrypt public key usage using PyCrypto?

+6
source share
2 answers

This is completely unsafe because you are using raw RSA without padding.

Your application needs a signature, so you do not have to deal with encryption and decryption. For example, PKCS # 1 v1.5 is a good protocol, although a signature is part of the data that needs to be added to what you want to prove authenticity.

To verify the PKCS # 1 v1.5 signature in Python, follow these steps:

 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA rsa_key = RSA.importKey(open(verification_key_file, "rb").read()) verifier = PKCS1_v1_5.new(rsa_key) h = SHA.new(data_to_verify) if verifier.verify(h, signature_received_with_the_data): print "OK" else: print "Invalid" 

I would strongly recommend modifying the PHP code so that it creates such a signature.

+5
source

Your function is correct. You just need to specify the path to your private key in order to decrypt instead of your public key. The public key is for encryption, the private key is for decryption.

 def _decrypt_rsa(decrypt_key_file, cipher_text): ''' Decrypt RSA encrypted package with private key :param decrypt_key_file: Private key :param cipher_text: Base64 encoded string to decrypt :return: String decrypted ''' from Crypto.PublicKey import RSA from base64 import b64decode key = open(decrypt_key_file, "r").read() rsakey = RSA.importKey(key) #optionally could use OAEP #from Crypto.Cipher import PKCS1_OAEP #rsakey = PKCS1_OAEP.new(rsakey) raw_cipher_data = b64decode(cipher_text) decrypted = rsakey.decrypt(raw_cipher_data) return decrypted 
0
source

Source: https://habr.com/ru/post/956580/


All Articles