decrypt file with PHP gnupg after encrypting using gpg4win - php

i am completely stuck with a pgp problem, but I guess it's more a logical than a technical problem - anyway, i don't get it.
The goal is to encrypt a file with gpg4win (www.gpg4win.de/index.html) and decrypt it with PHP (gnupg).
First thing I did, I've created a certificate with gpg4win, set a passphrase and encrypted a simple text file (ASCII). Then I upload the file and tried to decrypt it with the following code:
$content = file_get_contents("some-test-data.asc");
$gpg = new gnupg();
$gpg -> adddecryptkey("MYFINGERPRINT","my.pass.phrase");
$plain = $gpg -> decrypt($content);
var_dump($plain);
The result was:
bool(false)
What I am doing wrong? I've tried different code and suggestions, but always ended up with bool(false).
Are these methods not compatible, do I have to a different application?
I appreciate every little help I could get. Thanks alot!
P.S. PHP is compiled with gnupg
GPGme Version 1.4.2
Extension Version 1.3.3-dev

Problem solved. If anybody run into the same trouble, it's due to lag in the PHP Documentation:
string gnupg_decrypt ( resource $identifier , string $text )
If found the following comment in the comment section:
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.
So i've created a new key without password and everything works fine.

Related

PHP Cannot Install OpenSSL, Need to encrypt file with password

I've been requested from a customer to create a script that encrypts files with a password, and I wrote a script using OpenSSL
as follow:
$this->salt = openssl_random_pseudo_bytes(10);
$this->cryptoKey = openssl_pbkdf2($key, $this->salt, $this->cryptoKeyLength, $this->iterations,
$this->algorithm);
$this->iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->cipher));
The issue is, the customer doesn't have openssl and the hosting does not provide an user with enough rights to install php-openssl using yum i get I don't have enough privileges.
The website has https tho.
Is there another lib to use?
is there a way to use openssl as a class and include is as .php?
is there another function like this possibly native?
is there a weaker way to do the same possibly natively?
thanks
Would it be possible to install php on another machine and pass the request as a proxy and return the output, would it be a smart way out?

How to tell if phpseclib sftp response is a challenge with a password request when key doesn't match

Recently someone inadvertently changed the keyfile used for my ssh/sftp to a remote server. I deduced this when I tried to ssh to the server from the command line and I got challenged with a password request, which indicated that the key was no longer recognised.
How would I make my php program detect an unexpected password challenge? Currently I have this:
$sftp = new SFTP(self::DOMAIN_NAME);
$Key = new RSA();
$private_rsa_key = file_get_contents('/home/ddfs/.ssh/' . self::KEY_FILE);
$Key->loadKey($private_rsa_key);
$rc = $sftp->login(self::USER, $Key);
$errors = $sftp->getSFTPErrors();
At the moment I see $rc is set to FALSE and $errors is an empty array.
SSH initiated password change requests
SSH has a mechanism built into it for password resets. My reading of RFC4252 ยง 8 implies that SSH_MSG_USERAUTH_PASSWD_CHANGEREQ packets should only be sent in response to a "password" SSH_MSG_USERAUTH_REQUEST but who knows how the OpenSSH devs interpreted that section of the RFC.
Since you're doing public key authentication phpseclib would be sending a "publickey" SSH_MSG_USERAUTH_REQUEST so it seems like SSH_MSG_USERAUTH_PASSWD_CHANGEREQ wouldn't be a valid response, but again, who knows.
If the server did respond with a SSH_MSG_USERAUTH_PASSWD_CHANGEREQ packet than you could do $sftp->getErrors() (instead of getSFTPErrors) and look for one that starts with SSH_MSG_USERAUTH_PASSWD_CHANGEREQ:. Maybe even do $sftp->getLastError().
getSFTPErrors returns errors with the SFTP layer - not the SSH2 layer. SFTP as a protocol doesn't know about authentication - that's handled entirely by the SSH layer. ie. it's not SFTP errors you'd want to look at but SSH errors.
Reference code: https://github.com/phpseclib/phpseclib/blob/1.0.7/phpseclib/Net/SSH2.php#L2219
Other possible password request mechanisms
It's possible that password request isn't coming from SSH's built-in authentication mechanism. It's possible you're getting a SSH_MSG_USERAUTH_SUCCESS response from the "publickey" SSH_MSG_USERAUTH_REQUEST.
At this point I can see two possibilities:
It could be a banner message that you're seeing. You can get those by doing $sftp->getBannerMessage().
It's possible you're only seeing this error when you SSH into the server as opposed to SFTP'ing into it. ie. it's possible you wouldn't see the error unless you did $ssh->exec() or $ssh->write(). At this point the "error" could be communicated to you via stderr or stdout.
To know for sure I'd have to see the SSH logs. The phpseclib logs may or may not be sufficient. I mean you could do $sftp->exec('pwd'); or $sftp->read('[prompt]'); but my guess is that you're not already doing that. If you wanted to go that route you could do define('NET_SSH2_LOGGING', 2); and then echo $sftp->getLog() after you do either $sftp->exec() or $sftp->read().
The PuTTY logs might be more useful. To get them you can go to PuTTY->Session->Logging, check the "SSH packets" radio button and then connect as usual.
Unfortunately, OpenSSH does not, to the best of my knowledge, log the raw / decrypted SSH2 packets so OpenSSH isn't going to be too useful here.

PHP extension CLI crashing

I have c++ class used for encrypting a file - works fine on it's own. I wrapped it using swig for 5.6.x-nts-Win32-x64 PHP. Usage:
<?php
require("crypt.php");
$e = new CCrypt();
//(plain, encrypted)
if ($e->EncryptFile("sample","enc/sample")) {
print "Encrypted file\n";
}
$e = NULL;
print "Goodbye\n"
?>
Problem is this seems to work sometimes, with no consistent line in the extension code as to where it crashes when debugging. Error is corrupted heap. I am new to developing PHP extensions, and I'm wondering if this has to do with unsupported 64-bit PHP version, or something unique to CLI. Swig does not (yet) support PHP 7 :/
UPDATE
Forgot to mention encryption works fine if run as an executable from PHP.
Turned out to be my lack of understanding SWIG's implementation of STL. When I removed STL from the wrapper source, the extension worked as expected. I later added STL back in, albeit in proper SWIG fashion!

GnuPG isn't working in PHP with nginx

I think that probably I'm missing something, but I don't see it right now. I want create a simple form where users can encrypt automatically messages between them (form message to user2 -> encrypt(message) -> user2 receive it and decrypt). I'm using nginx, I installed gnupg following their instructions and add it to my php.ini (now it shows that GnuPG is enabled with GPGME Version 1.4.3 and Extension Version 1.3.6) I want use a specific keyring located at /usr/share/nginx/.gnupg I tried the following code:
$iterator = new gnupg_keylistiterator("developer");
foreach($iterator as $fingerprint => $userid) {
echo $fingerprint." -> " . $userid . "\n";
}
var_dump($iterator);
And I just obtain the following response from var_dump:
object(gnupg_keylistiterator)#1 (0) { }
Maybe my question is an idiot question, but I never used gnupg in php and I want learning, but I'm stunk since yesterday and I don't understand why it doesn't work...
Thanks for your time
The most common issue is that you imported the keys to another keyring than later is searched for keys. GnuPG uses a per-(system)-user "GnuPG home directory", each containing individual keyrings. If you import a key as the administrator or a developer you import the key to your own keyring, while usually the web server running the PHP application is executed in another user context and will not find this key, resulting in an empty result when listing the keys from within PHP.
You can set this by setting up an environment variable before initializing the GnuPG binding.
putenv("GNUPGHOME=/tmp"); // Set GnuPG home directory to the temp folder
$res = gnupg_init(); // Initialize GnuPG
Obviously /tmp does not actually qualify as a reasonable directory, choose something where your application stores application data anyway. It should not be a directory accessible through HTTP.
As an alternative, gnupg_import($res, $pubkey) the key before using it (but this will result in some performance penalty for importing the key).

Is it possible to decrypt files encrypted with php mcrypt_encode with third party utilities?

I am inexperienced with symmetric encryption. I am encrypting a pdf file in php using the following code:
$source_filepath = RB::get('docroot') . RB::get('baseUrl') . '/submissions/' . $this->_filename;
$encrypted_filepath = $source_filepath . '.nc';
$pdf_data = file_get_contents($source_filepath);
$encrypted_data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, '1234567812345678', $pdf_data, MCRYPT_MODE_ECB);
file_put_contents($encrypted_filepath, $encrypted_data);
Then I need to decrypt it outside of php, potentially using a desktop application/utility on another computer. I have attempted to decrypt the file with the aescrypt utility (http://www.aescrypt.com/) which tells me:
"Error: Bad file header (not aescrypt file or is corrupted? [c, fffffff0, fffffffe])"
as well as the mcrypt command which tells me:
File thefile.pdf.nc was NOT decrypted successfully.
I have yet to be able to decrypt anything encrypted with encrypt outside of php. I have tried using blowfish and decrypting it with bcrypt (http://bcrypt.sourceforge.net/) as well with similar results. I suspect my ignorance of how encryption works is to blame but any help or education would be appreciated. Thanks.
I am encrypting a pdf file in php using the following code:
The reason your getting an error from aescrypt is because the file you are writing has nothing to with the AEScrypt file format. Fortunately the developers of AESCrypt have provided very detailled instructions on their file format.
If after implementing that you're still having problems, then you could try the AESCrypt mailing list and failing that you could even contact the developers and offer to sponsor development of a cmpatible encryptor/decryptor in PHP.
I'm don't know PHP or mcrypt but just based on the calling line I suspect you could decrypt the file with the openssl command-line utility. The following example should close to what you need:
openssl aes-128-ecb -d -K 303132333435363738303132333435363738 -iv 00000000000000000000000000000000 -P -nopad -nosalt -in cipherfile -out plainfile
NOTE: You'll have to strip off any padding yourself. mcrypt_encrypt apparently tacks on '\0' characters to pad the data to a multiple of the blocksize.

Categories