singpolyma / openpgp-php

OpenPGP.php is a pure-PHP implementation of the OpenPGP Message Format (RFC 4880).
http://singpolyma.github.io/openpgp-php/
The Unlicense
179 stars 69 forks source link

Need help with decrypting a file #122

Closed ericclaeren closed 2 years ago

ericclaeren commented 2 years ago

Hi,

First of all, thank you for writing and maintaining this package!

I would like to decrypt an external provided file within an applicaiton.

Was starting out with a test, which is just with a simple message.txt with some text. I have encoded it on CLI with: gpg --cipher-algo AES256 --output message.txt.gpg --encrypt -u <ID> message.txt

The key used for encrypting is has the default GPG key generate settings and has no paraphrase.

Tried to sort of reverse engineer the logic for encrypting, but it returns an exception: Exception : Not an asymmetrically encrypted message

        $content = file_get_contents($file->getPathname());
        $packet = new OpenPGP_LiteralDataPacket($content, ['format' => 'b', 'filename' => $file->getFilename()]);
        $message = new OpenPGP_Message([$packet]);

Guess this is because the OpenPGP_Crypt_Symmetric::encrypt() method, does quite some logic

      if($pass instanceof OpenPGP_PublicKeyPacket) {
        if(!in_array($pass->algorithm, array(1,2,3))) throw new Exception("Only RSA keys are supported.");
        $crypt_rsa = new OpenPGP_Crypt_RSA($pass);
        $rsa = $crypt_rsa->public_key();
        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $esk = $rsa->encrypt(chr($symmetric_algorithm) . $key . pack('n', self::checksum($key)));
        $esk = pack('n', OpenPGP::bitlength($esk)) . $esk;
        array_unshift($encrypted, new OpenPGP_AsymmetricSessionKeyPacket($pass->algorithm, $pass->fingerprint(), $esk));
      }

Is there an easier way to decrypt the file contents or do I have to reverse engineer the packets generated from ::encrypt to decrypt a already encrypted file? Maybe I'm overthinking this or missing something.

Thanks!

ericclaeren commented 2 years ago

Fixed, instead of creating the datapacket myself, i parsed the file by openPGP_Message::parse and that created the correct class. Marked as closed.