md1980
md1980

Reputation: 339

check if file is a valid pgp encrypted file

I need to check to see if a file is a valid pgp encrypted file or not. Some pgp files that we get have an extension of pgp and some dont. I need to check to see which of the files are pgp encrypted files and which are not. Please let me know if there is a way to tell.

Upvotes: 5

Views: 5407

Answers (2)

bignose
bignose

Reputation: 32347

The python-gpgme library is a Pythonic wrapper for GPGME, the library allowing programmatic GnuPG access.

If you have some files that may or may not be GnuPG encrypted:

$ head --bytes=1024k < /dev/urandom > lorem
$ head --bytes=1024k < /dev/urandom | gpg --encrypt --recipient DEADBEEF > ipsum

With the gpgme module you can attempt to decrypt the files:

import gpgme
import io

context = gpgme.Context()
for infile_path in ['lorem', 'ipsum']:
    with open(infile_path, 'rb') as infile:
        outfile = io.BytesIO()
        try:
            context.decrypt(infile, outfile)
        except gpgme.GpgmeError as exc:
            if exc.code == gpgme.ERR_NO_DATA:
                print(
                    "Not a GnuPG-encrypted file: ‘{path}’ ({error})".format(
                        path=infile.name, error=exc.strerror))
            else:
                print(
                    "Error decrypting file: ‘{path}’ ({error})".format(
                        path=infile.name, error=exc.strerror))
        else:
            print("Successfully decrypted: ‘{path}’".format(
                path=infile.name))

That lets you handle three conditions:

  • The gpgme.Context.decrypt method fails, and the error code is gpgme.ERR_NO_DATA. This means the data stream was not recognised as GnuPG-encrypted data.

  • The gpgme.Context.decrypt method fails for some other reason. You'll need to decide which other errors you care about here.

  • The gpgme.Context.decrypt method succeeds. Obviously, the file is a correctly-encrypted file.

Upvotes: 3

Tomato
Tomato

Reputation: 81

The only certain way is to attempt decrypting the file (e.g. with gpg) and interpret the error output. Unless you limit input to ascii-armored files, in that case you can check for the armor.

Upvotes: 4

Related Questions