pgp encryption and decryption php code example

Example 1: php password encryption and decryption

function encryptPass($password) {
    $sSalt = '20adeb83e85f03cfc84d0fb7e5f4d290';
    $sSalt = substr(hash('sha256', $sSalt, true), 0, 32);
    $method = 'aes-256-cbc';

    $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);

    $encrypted = base64_encode(openssl_encrypt($password, $method, $sSalt, OPENSSL_RAW_DATA, $iv));
    return $encrypted;
}

function decryptPass($password) {
    $sSalt = '20adeb83e85f03cfc84d0fb7e5f4d290';
    $sSalt = substr(hash('sha256', $sSalt, true), 0, 32);
    $method = 'aes-256-cbc';

    $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);

    $decrypted = openssl_decrypt(base64_decode($password), $method, $sSalt, OPENSSL_RAW_DATA, $iv);
    return $decrypted;
}

Example 2: php pgp

<?php

 // Using PHP with PGP.
 // (c) Kelv 2000

 $username = "dummy";       // Your username on the server
 $pgp="/usr/local/bin/gpg"; // path to GnuPG

 // Where the encrypted mail comes from. Dummy address from your keyring.
 $from="Example.com website <[email protected]>";

 // The recipient. This is the imported address from your public key.
 $recp="Example orders <[email protected]>";

 // The data to be encrypted
 $data="Text that will be encrypted"; 

 $command = 'echo "'.$data.'" | '.$pgp.' -a --always-trust --batch "
 $command.= '--no-secmem-warning -e -u "'.$from.'" -r "'.$recp.'"';
 $oldhome = getEnv("HOME");

 putenv("HOME=/home/$username");
 $result = exec($command, $encrypted, $errorcode);
 putenv("HOME=$oldhome");

 $message = implode("\n", $encrypted); 
 // $message now contains the encrypted data.

 $subject="New order from example.com website";
 $header="From: {$from}";

 mail($recp,$subject,$message,$header);

?>

Tags:

Php Example