Example #1
-1
 /**
  * Tries to decrypt an S/MIME message using a private key
  * 
  * @param array  &$info       The array of information about a message
  * @param array  $structure   The structure of this part
  * @param array  $smime_pair  An associative array containing an S/MIME certificate, private key and password
  * @return boolean  If the message was decrypted
  */
 private static function handleSMIMEDecryption(&$info, $structure, $smime_pair)
 {
     $plaintext_file = tempnam('', '__fMailbox_');
     $ciphertext_file = tempnam('', '__fMailbox_');
     $headers = array();
     $headers[] = "Content-Type: " . $structure['type'] . '/' . $structure['subtype'];
     $headers[] = "Content-Transfer-Encoding: " . $structure['encoding'];
     $header = "Content-Disposition: " . $structure['disposition'];
     foreach ($structure['disposition_fields'] as $field => $value) {
         $header .= '; ' . $field . '="' . $value . '"';
     }
     $headers[] = $header;
     file_put_contents($ciphertext_file, join("\r\n", $headers) . "\r\n\r\n" . $structure['data']);
     $private_key = openssl_pkey_get_private($smime_pair['private_key']->read(), $smime_pair['password']);
     $certificate = $smime_pair['certificate']->read();
     $result = openssl_pkcs7_decrypt($ciphertext_file, $plaintext_file, $certificate, $private_key);
     unlink($ciphertext_file);
     if (!$result) {
         unlink($plaintext_file);
         return FALSE;
     }
     $contents = file_get_contents($plaintext_file);
     $info['raw_message'] = $contents;
     $info = self::handlePart($info, self::parseStructure($contents));
     $info['decrypted'] = TRUE;
     unlink($plaintext_file);
     return TRUE;
 }
Example #2
-1
<?php

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    var_dump($errstr);
}
set_error_handler("myErrorHandler");
$a = 1;
$b = 1;
$c = new stdclass();
$d = new stdclass();
var_dump(openssl_pkcs7_decrypt($a, $b, $c, $d));
var_dump($c);
var_dump(openssl_pkcs7_decrypt($b, $b, $b, $b));
var_dump(openssl_pkcs7_decrypt($a, $b, "", ""));
var_dump(openssl_pkcs7_decrypt($a, $b, true, false));
var_dump(openssl_pkcs7_decrypt($a, $b, 0, 0));
echo "Done\n";
Example #3
-1
 /**
  * Decrypt an S/MIME encrypted message using a private/public keypair
  * and a passhprase.
  *
  * @param string $text   The text to be decrypted.
  * @param array $params  The parameters needed for decryption.
  * <pre>
  * Parameters:
  * ===========
  * 'type'        =>  'message' (REQUIRED)
  * 'pubkey'      =>  public key. (REQUIRED)
  * 'privkey'     =>  private key. (REQUIRED)
  * 'passphrase'  =>  Passphrase for Key. (REQUIRED)
  * </pre>
  *
  * @return string  The decrypted message.
  * @throws Horde_Crypt_Exception
  */
 protected function _decryptMessage($text, $params)
 {
     /* Check for required parameters. */
     if (!isset($params['pubkey']) || !isset($params['privkey']) || !array_key_exists('passphrase', $params)) {
         throw new Horde_Crypt_Exception(Horde_Crypt_Translation::t("A public S/MIME key, private S/MIME key, and passphrase are required to decrypt a message."));
     }
     /* Create temp files for input/output. */
     $input = $this->_createTempFile('horde-smime');
     $output = $this->_createTempFile('horde-smime');
     /* Store message in file. */
     file_put_contents($input, $text);
     unset($text);
     $privkey = is_null($params['passphrase']) ? $params['privkey'] : array($params['privkey'], $params['passphrase']);
     if (openssl_pkcs7_decrypt($input, $output, $params['pubkey'], $privkey)) {
         return file_get_contents($output);
     }
     throw new Horde_Crypt_Exception(Horde_Crypt_Translation::t("Could not decrypt S/MIME data."));
 }
    public function testEncryptThenSignMessage()
    {
        $message = Swift_SignedMessage::newInstance('Wonderful Subject')->setFrom(array('*****@*****.**' => 'John Doe'))->setTo(array('*****@*****.**', '*****@*****.**' => 'A name'))->setBody('Here is the message itself');
        $originalMessage = $this->cleanMessage($message->toString());
        $signer = Swift_Signers_SMimeSigner::newInstance();
        $signer->setSignCertificate($this->samplesDir . 'smime/sign.crt', $this->samplesDir . 'smime/sign.key');
        $signer->setEncryptCertificate($this->samplesDir . 'smime/encrypt.crt');
        $signer->setSignThenEncrypt(false);
        $message->attachSigner($signer);
        $messageStream = $this->newFilteredStream();
        $message->toByteStream($messageStream);
        $messageStream->commit();
        $entityString = $messageStream->getContent();
        $headers = self::getHeadersOfMessage($entityString);
        if (!($boundary = $this->getBoundary($headers['content-type']))) {
            return false;
        }
        $expectedBody = <<<OEL
This is an S/MIME signed message

--{$boundary}
(?P<encrypted_message>MIME-Version: 1\\.0
Content-Disposition: attachment; filename="smime\\.p7m"
Content-Type: application/(x\\-)?pkcs7-mime; smime-type=enveloped-data; name="smime\\.p7m"
Content-Transfer-Encoding: base64

(?:^[a-zA-Z0-9\\/\\r\\n+]*={0,2})


)--{$boundary}
Content-Type: application/(x\\-)?pkcs7-signature; name="smime\\.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime\\.p7s"

(?:^[a-zA-Z0-9\\/\\r\\n+]*={0,2})

--{$boundary}--
OEL;
        if (!$this->assertValidVerify($expectedBody, $messageStream)) {
            return false;
        }
        $expectedBody = str_replace("\n", "\r\n", $expectedBody);
        if (!preg_match('%' . $expectedBody . '*%m', $entityString, $entities)) {
            $this->fail('Failed regex match.');
            return false;
        }
        $messageStreamClean = new Swift_ByteStream_TemporaryFileByteStream();
        $messageStreamClean->write($entities['encrypted_message']);
        $decryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream();
        if (!openssl_pkcs7_decrypt($messageStreamClean->getPath(), $decryptedMessageStream->getPath(), 'file://' . $this->samplesDir . 'smime/encrypt.crt', array('file://' . $this->samplesDir . 'smime/encrypt.key', 'swift'))) {
            $this->fail(sprintf('Decrypt of the message failed. Internal error "%s".', openssl_error_string()));
        }
        $this->assertEquals($originalMessage, $decryptedMessageStream->getContent());
        unset($messageStreamClean, $messageStream, $decryptedMessageStream);
    }
Example #5
-1
 public static function toOutputArray(array &$response, \GO\Email\Model\ImapMessage $imapMessage)
 {
     if ($imapMessage->content_type == 'application/x-pkcs7-mime') {
         $imapMessage->content_type = 'application/pkcs7-mime';
     }
     if ($imapMessage->content_type == 'application/pkcs7-mime' && isset($imapMessage->content_type_attributes['smime-type']) && $imapMessage->content_type_attributes['smime-type'] == 'signed-data') {
         //signed data but not in clear text. Outlook has this option.
         $outfile = \GO\Base\Fs\File::tempFile();
         $imapMessage->getImapConnection()->save_to_file($imapMessage->uid, $outfile->path());
         $verifyOutfile = \GO\Base\Fs\File::tempFile();
         //			$cmd = '/usr/bin/openssl smime -verify -in ' . $outfile->path() . ' -out ' . $verifyOutfile->path();
         //			exec($cmd);
         //
         //PHP can't output the verified data without the signature without
         //suppling the extracerts option. We generated a dummy certificate for
         //this.
         openssl_pkcs7_verify($outfile->path(), null, "/dev/null", array(), GO::config()->root_path . "modules/smime/dummycert.pem", $verifyOutfile->path());
         $message = \GO\Email\Model\SavedMessage::model()->createFromMimeData($verifyOutfile->getContents());
         //remove temp files
         $outfile->delete();
         $verifyOutfile->delete();
         $newResponse = $message->toOutputArray(true);
         unset($newResponse['to']);
         unset($newResponse['cc']);
         foreach ($newResponse as $key => $value) {
             if (!empty($value) || $key == 'attachments') {
                 $response[$key] = $value;
             }
         }
         //			$response['path'] = $outfile->stripTempPath();
         return;
     }
     if ($imapMessage->content_type == 'application/pkcs7-mime') {
         $encrypted = !isset($imapMessage->content_type_attributes['smime-type']) || $imapMessage->content_type_attributes['smime-type'] != 'signed-data';
         if ($encrypted) {
             GO::debug("Message is encrypted");
             $cert = Model\Certificate::model()->findByPk($imapMessage->account->id);
             if (!$cert || empty($cert->cert)) {
                 GO::debug('SMIME: No private key at all found for this account');
                 $response['htmlbody'] = GO::t('noPrivateKeyForDecrypt', 'smime');
                 return false;
             }
             if (isset($_REQUEST['password'])) {
                 GO::session()->values['smime']['passwords'][$imapMessage->account->id] = $_REQUEST['password'];
             }
             if (!isset(GO::session()->values['smime']['passwords'][$imapMessage->account->id])) {
                 $response['askPassword'] = true;
                 GO::debug("Need to ask for password");
                 return false;
             }
         }
         $attachments = $imapMessage->getAttachments();
         $att = array_shift($attachments);
         //			array (
         //      'type' => 'application',
         //      'subtype' => 'pkcs7-mime',
         //      'smime-type' => 'enveloped-data',
         //      'name' => 'smime.p7m',
         //      'id' => false,
         //      'encoding' => 'base64',
         //      'size' => '2302',
         //      'md5' => false,
         //      'disposition' => false,
         //      'language' => false,
         //      'location' => false,
         //      'charset' => false,
         //      'lines' => false,
         //      'number' => 1,
         //      'extension' => 'p7m',
         //      'human_size' => '2,2 KB',
         //      'tmp_file' => false,
         //    )
         $infile = \GO\Base\Fs\File::tempFile();
         $outfile = \GO\Base\Fs\File::tempFile();
         //$outfilerel = $reldir . 'unencrypted.txt';
         if ($encrypted) {
             GO::debug('Message is encrypted');
             //				$imapMessage->getImapConnection()->save_to_file($imapMessage->uid, $infile->path(), 'TEXT', 'base64');
             //				throw new \Exception($infile->path());
             if (!$imapMessage->saveToFile($infile->path())) {
                 throw new \Exception("Could not save IMAP message to file for decryption");
             }
             $password = GO::session()->values['smime']['passwords'][$imapMessage->account->id];
             openssl_pkcs12_read($cert->cert, $certs, $password);
             if (empty($certs)) {
                 //password invalid
                 $response['askPassword'] = true;
                 GO::debug("Invalid password");
                 return false;
             }
             $return = openssl_pkcs7_decrypt($infile->path(), $outfile->path(), $certs['cert'], array($certs['pkey'], $password));
             $infile->delete();
             if (!$return || !$outfile->exists() || !$outfile->size()) {
                 $response['htmlbody'] = GO::t('decryptionFailed', 'smime') . '<br />';
                 while ($str = openssl_error_string()) {
                     $response['htmlbody'] .= '<br />' . $str;
                 }
                 GO::debug("Decryption failed");
                 return false;
             } else {
                 //check if also signed
                 $data = $outfile->getContents();
                 if (strpos($data, 'signed-data')) {
                     $verifyOutfile = \GO\Base\Fs\File::tempFile();
                     openssl_pkcs7_verify($outfile->path(), null, "/dev/null", array(), GO::config()->root_path . "modules/smime/dummycert.pem", $verifyOutfile->path());
                     $outfile = $verifyOutfile;
                 }
                 $message = \GO\Email\Model\SavedMessage::model()->createFromMimeData($outfile->getContents());
                 $newResponse = $message->toOutputArray(true);
                 unset($newResponse['to']);
                 unset($newResponse['to_string']);
                 unset($newResponse['cc']);
                 foreach ($newResponse as $key => $value) {
                     if (!empty($value) || $key == 'attachments') {
                         $response[$key] = $value;
                     }
                 }
                 $response['smime_encrypted'] = true;
                 //$response['path']=$outfile->stripTempPath();
                 $outfile->delete();
             }
         } else {
             GO::debug('Message is NOT encrypted');
         }
     }
 }
Example #6
-1
    die("failed to get a temporary filename!");
}
$outfile2 = tempnam("/tmp", "ssl");
if ($outfile2 === false) {
    die("failed to get a temporary filename!");
}
$single_cert = "file://" . dirname(__FILE__) . "/cert.crt";
$privkey = "file://" . dirname(__FILE__) . "/private.key";
$multi_certs = array($single_cert, $single_cert);
$assoc_headers = array("To" => "test@test", "Subject" => "testing openssl_pkcs7_encrypt()");
$headers = array("test@test", "testing openssl_pkcs7_encrypt()");
$empty_headers = array();
$wrong = "wrong";
$empty = "";
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $single_cert, $headers));
var_dump(openssl_pkcs7_decrypt($outfile, $outfile2, $single_cert, $privkey));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $single_cert, $assoc_headers));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $single_cert, $empty_headers));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $single_cert, $wrong));
var_dump(openssl_pkcs7_encrypt($wrong, $outfile, $single_cert, $headers));
var_dump(openssl_pkcs7_encrypt($empty, $outfile, $single_cert, $headers));
var_dump(openssl_pkcs7_encrypt($infile, $empty, $single_cert, $headers));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $wrong, $headers));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $empty, $headers));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $single_cert, $empty));
var_dump(openssl_pkcs7_encrypt($infile, $outfile, $multi_certs, $headers));
if (file_exists($outfile)) {
    echo "true\n";
    unlink($outfile);
}
if (file_exists($outfile2)) {
Example #7
-1
 public function decrypt($encMsg)
 {
     $invoice = time();
     $filehash = $invoice . '_' . time();
     $respfile = $this->decryptPath . 'resp_' . $filehash;
     $decfile = $this->decryptPath . 'dec_' . $filehash;
     $msgfile = $this->decryptPath . 'msg_' . $filehash;
     file_put_contents($respfile, $encMsg);
     $strOri = "MIME-Version: 1.0\nContent-Disposition: attachment; filename=\"smime.p7m\"\nContent-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"\nContent-Transfer-Encoding: base64\n\n";
     $enc = file_get_contents($respfile);
     $enc = wordwrap($enc, 64, "\n", true);
     if ($fp = fopen($decfile, "w")) {
         fwrite($fp, $strOri . $enc);
         fclose($fp);
     } else {
         error_log("Can't write file " . $decfile);
         return false;
     }
     $key = file_get_contents($this->merchantPublicKey);
     $key_private = array(file_get_contents($this->merchantPrivateKey), $this->merchantPassword);
     if (openssl_pkcs7_decrypt($decfile, $msgfile, $key, $key_private)) {
         return file_get_contents($msgfile);
     } else {
         error_log("Can't decrypt on Twoc2pPayment Library =>" . $decfile);
         return false;
     }
 }
Example #8
-1
$encrypted = tempnam("/tmp", "ssl");
if ($encrypted === false) {
    die("failed to get a temporary filename!");
}
$outfile = tempnam("/tmp", "ssl");
if ($outfile === false) {
    unlink($outfile);
    die("failed to get a temporary filename!");
}
$single_cert = "file://" . dirname(__FILE__) . "/cert.crt";
$headers = array("test@test", "testing openssl_pkcs7_encrypt()");
$wrong = "wrong";
$empty = "";
openssl_pkcs7_encrypt($infile, $encrypted, $single_cert, $headers);
var_dump(openssl_pkcs7_decrypt($encrypted, $outfile, $single_cert, $privkey));
var_dump(openssl_pkcs7_decrypt($encrypted, $outfile, $single_cert, $wrong));
var_dump(openssl_pkcs7_decrypt($encrypted, $outfile, $wrong, $privkey));
var_dump(openssl_pkcs7_decrypt($encrypted, $outfile, null, $privkey));
var_dump(openssl_pkcs7_decrypt($wrong, $outfile, $single_cert, $privkey));
var_dump(openssl_pkcs7_decrypt($empty, $outfile, $single_cert, $privkey));
var_dump(openssl_pkcs7_decrypt($encrypted, $empty, $single_cert, $privkey));
var_dump(openssl_pkcs7_decrypt($encrypted, $outfile, $empty, $privkey));
var_dump(openssl_pkcs7_decrypt($encrypted, $outfile, $single_cert, $empty));
if (file_exists($encrypted)) {
    echo "true\n";
    unlink($encrypted);
}
if (file_exists($outfile)) {
    echo "true\n";
    unlink($outfile);
}
Example #9
-1
 private function _decryptFile(\GO\Base\Fs\File $srcFile, \GO\Email\Model\Account $account)
 {
     $data = $srcFile->getContents();
     if (strpos($data, "enveloped-data") || strpos($data, 'Encrypted Message')) {
         $cert = \GO\Smime\Model\Certificate::model()->findByPk($account->id);
         $password = \GO::session()->values['smime']['passwords'][$_REQUEST['account_id']];
         openssl_pkcs12_read($cert->cert, $certs, $password);
         $decryptedFile = \GO\Base\Fs\File::tempFile();
         $ret = openssl_pkcs7_decrypt($srcFile->path(), $decryptedFile->path(), $certs['cert'], array($certs['pkey'], $password));
         if (!$decryptedFile->exists()) {
             throw new \Exception("Could not decrypt message: " . openssl_error_string());
         }
         $decryptedFile->move($srcFile->parent(), $srcFile->name());
     }
 }
Example #10
-2
function decrypt($encText, $key, $key_private)
{
    $msgfile = "msg.txt";
    $encfile = "enc.txt";
    $decfile = "dec.txt";
    file_put_contents($encfile, $encText);
    // ¹Óä¿Åìŧä»ã¹ msg.txt Merchant's private key
    $strOri = "MIME-Version: 1.0\nContent-Disposition: attachment; filename=\"smime.p7m\"\nContent-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"\nContent-Transfer-Encoding: base64\n\n";
    $enc = file_get_contents($encfile);
    $enc = wordwrap($enc, 64, "\n", true);
    $fp = fopen($encfile, "w");
    fwrite($fp, $strOri . $enc);
    fclose($fp);
    if (openssl_pkcs7_decrypt($encfile, $decfile, $key, $key_private)) {
        // echo "<br><b>Successfully decrypted: </b>";
        return file_get_contents($decfile);
    } else {
        echo "Cannot Decrypt";
        return "Cannot Decrypt";
    }
}
function decrypt($encFile, $decFile, $key, $key_private)
{
    $strOri = "MIME-Version: 1.0\nContent-Disposition: attachment; filename=\"smime.p7m\"\nContent-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"\nContent-Transfer-Encoding: base64\n\n";
    $enc = file_get_contents($encFile);
    $enc = wordwrap($enc, 64, "\n", true);
    $fp = fopen($encFile, "w");
    fwrite($fp, $strOri . $enc);
    fclose($fp);
    if (openssl_pkcs7_decrypt($encFile, $decFile, $key, $key_private)) {
        echo "<br><b>Successfully decrypted: </b>";
        echo file_get_contents($decFile);
    } else {
        echo "Cannot Decrypt";
    }
}