Is there a way to decrypt an encrypted file using Python libraries?

730 views Asked by At

I was given a task wherein I am to write a python script that can be used to decrypt some encrypted files.

I was given with

  1. examplefile.pgp (Encrypted file having text data)
  2. examplepublic.asc (Public Key in asc format)
  3. example.pkr (Public keyring)
  4. example.skr (Secret Keyring)
  5. passphrase

The task is to retrieve the test by decrypting examplefile.pgp

I tried the following script to first validate the public key

import pgpy
emsg = pgpy.PGPMessage.from_file(r"examplefile.pgp")
key,_  = pgpy.PGPKey.from_file(r"examplepublic.asc")
print(key)

This worked fine and public key was printed but I cant use it for decryption so I tried this following script

import gnupg
gpg = gnupg.GPG(gnupghome=r"C:\Program Files (x86)\GnuPG",
gpgbinary = r"C:\Program Files (x86)\GnuPG\bin\gpg.exe",
keyring=r"example.pkr",
secret_keyring=r"example.skr")


with open(r"examplefile.pgp",'rb') as f:
    status = gpg.decrypt_file(f,passphrase='passphrase',output='output.txt')
    print(status.status)

But this is returning the error of "no secret key"

I tried doing the process manually using Cleopatra and it worked using the above keys.

Can anyone help me on how I can decrypt text using .pkr and .skr files?

1

There are 1 answers

1
Rahul M On

Resolved this issue. Wanted to post the fix incase someone wants to know.

The code in the question is correct, but for it to work, you need to download the Kleopatra tool.

Once you open Kleopatra, you will need to import both the public and secret keyring and verify them as certificates. Once this is done, the above code should work.