function encrypt($key, $datFile, $encFile) { if (openssl_pkcs7_encrypt($datFile, $encFile, $key, array())) { echo "<b>Successfully encrypted: </b>"; $tempStr = file_get_contents($encFile); $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"; $fp = fopen($encFile, "w"); fwrite($fp, str_replace($strOri, "", $tempStr)); fclose($fp); echo str_replace($strOri, "", $encFile) . "<br/><br/>"; echo "<b>Encrypted string again, with \"\\n\" replaced with <br> and \"\\r\" replaced with [CR]:</b><br>"; $fp = fopen($encFile, 'r'); while (false !== ($char = fgetc($fp))) { if ($char == "\n") { echo "<br>"; } else { if ($char == "\r") { echo "[CR]"; } } echo $char; } } else { echo "Cannot Encrypt <br/>"; } }
private function encrypt($invoice, $msg) { $key = file_get_contents($this->serverPublicKey); //public key for encrypt. This is 123's public key $filehash = $invoice . '_' . time(); $encfile = $this->encryptPath . 'enc_' . $filehash; $msgfile = $this->encryptPath . 'msg_' . $filehash; try { file_put_contents($msgfile, $msg); if (openssl_pkcs7_encrypt($msgfile, $encfile, $key, array())) { $tempStr = file_get_contents($encfile); $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"; $pos = strpos($tempStr, "base64"); $tempStr = trim(substr($tempStr, $pos + 6)); unlink($encfile); unlink($msgfile); return str_replace($strOri, "", $tempStr); } else { echo "Error"; error_log("Encrypt error on One23Payment Library =>" . $msgfile); unlink($encfile); return false; } } catch (Exception $e) { echo $e->getMessage(); } }
/** * Sign and Envelope the passed data string, returning a PKCS7 blob that can be posted to PayPal. * Make sure the passed data string is seperated by UNIX linefeeds (ASCII 10, '\n'). * * @param string The candidate for signature and encryption * @param string The file path to the EWP(merchant) certificate * @param string The file path to the EWP(merchant) private key * @param string The EWP(merchant) private key password * @param string The file path to the PayPal Certificate * @return array Contains a bool status, error_msg, error_no, and an encrypted string: encryptedData if successfull * * @access public * @static */ function signAndEncrypt($dataStr_, $ewpCertPath_, $ewpPrivateKeyPath_, $ewpPrivateKeyPwd_, $paypalCertPath_) { $dataStrFile = realpath(tempnam('/tmp', 'pp_')); $fd = fopen($dataStrFile, 'w'); if (!$fd) { $error = "Could not open temporary file {$dataStrFile}."; return array("status" => false, "error_msg" => $error, "error_no" => 0); } fwrite($fd, $dataStr_); fclose($fd); $signedDataFile = realpath(tempnam('/tmp', 'pp_')); if (!@openssl_pkcs7_sign($dataStrFile, $signedDataFile, "file://{$ewpCertPath_}", array("file://{$ewpPrivateKeyPath_}", $ewpPrivateKeyPwd_), array(), PKCS7_BINARY)) { unlink($dataStrFile); unlink($signedDataFile); $error = "Could not sign data: " . openssl_error_string(); return array("status" => false, "error_msg" => $error, "error_no" => 0); } unlink($dataStrFile); $signedData = file_get_contents($signedDataFile); $signedDataArray = explode("\n\n", $signedData); $signedData = $signedDataArray[1]; $signedData = base64_decode($signedData); unlink($signedDataFile); $decodedSignedDataFile = realpath(tempnam('/tmp', 'pp_')); $fd = fopen($decodedSignedDataFile, 'w'); if (!$fd) { $error = "Could not open temporary file {$decodedSignedDataFile}."; return array("status" => false, "error_msg" => $error, "error_no" => 0); } fwrite($fd, $signedData); fclose($fd); $encryptedDataFile = realpath(tempnam('/tmp', 'pp_')); if (!@openssl_pkcs7_encrypt($decodedSignedDataFile, $encryptedDataFile, file_get_contents($paypalCertPath_), array(), PKCS7_BINARY)) { unlink($decodedSignedDataFile); unlink($encryptedDataFile); $error = "Could not encrypt data: " . openssl_error_string(); return array("status" => false, "error_msg" => $error, "error_no" => 0); } unlink($decodedSignedDataFile); $encryptedData = file_get_contents($encryptedDataFile); if (!$encryptedData) { $error = "Encryption and signature of data failed."; return array("status" => false, "error_msg" => $error, "error_no" => 0); } unlink($encryptedDataFile); $encryptedDataArray = explode("\n\n", $encryptedData); $encryptedData = trim(str_replace("\n", '', $encryptedDataArray[1])); return array("status" => true, "encryptedData" => $encryptedData); }
function encrypt($key, $msg) { $msgfile = "msg.txt"; $encfile = "enc.txt"; $decfile = "dec.txt"; file_put_contents($msgfile, $msg); if (openssl_pkcs7_encrypt($msgfile, $encfile, $key, array())) { echo "<b>Successfully encrypted: </b>"; $tempStr = file_get_contents($encfile); $pos = strpos($tempStr, "base64"); $tempStr = trim(substr($tempStr, $pos + 6)); return str_replace($strOri, "", $tempStr); } else { echo "Cannot Encrypt <br/>"; return "Cannot Encrypt"; } }
public function encryptData($data) { if ($this->certificateID == '' || !isset($this->certificate) || !isset($this->paypalCertificate)) { return FALSE; } sfContext::getInstance()->getLogger()->warning('esPaypalButton: data ...'); $parameters = array(); $data['cert_id'] = $this->certificateID; foreach ($data as $key => $value) { $parameters[] = "{$key}={$value}"; sfContext::getInstance()->getLogger()->warning("{$key}={$value}"); } $clearText = join("\n", $parameters); sfContext::getInstance()->getLogger()->warning($clearText); $clearFile = tempnam('/tmp', 'clear'); $signedFile = tempnam('/tmp', 'signed'); $encryptedFile = tempnam('/tmp', 'encrypted'); $out = fopen($clearFile, 'wb'); fwrite($out, $clearText); fclose($out); if (!openssl_pkcs7_sign($clearFile, $signedFile, $this->certificate, $this->privateKey, array(), PKCS7_BINARY)) { return FALSE; } $signedData = explode("\n\n", file_get_contents($signedFile)); $out = fopen($signedFile, 'wb'); fwrite($out, base64_decode($signedData[1])); fclose($out); if (!openssl_pkcs7_encrypt($signedFile, $encryptedFile, $this->paypalCertificate, array(), PKCS7_BINARY)) { return FALSE; } $encryptedData = explode("\n\n", file_get_contents($encryptedFile)); $encryptedText = $encryptedData[1]; @unlink($clearFile); @unlink($signedFile); @unlink($encryptedFile); return sprintf('-----BEGIN PKCS7-----%s-----END PKCS7-----', trim(str_replace("\n", "", $encryptedText))); }
/** * Use our encryption certificate to encrypt the given parameters. * * @param array $params * @return string */ public function encrypt(array $params) { // Make sure we have the data we need if (empty($this->certificate_id) || empty($this->public_cert) || empty($this->paypal_cert)) { throw new SecurityException('Please set your public certificate, PayPal certificate and certificate ID'); } // Compose clear text data $encrypted_text = ''; $clear_text = 'cert_id=' . $this->certificate_id; foreach ($params as $key => $param) { $clear_text .= sprintf("\n%s=%s", $key, $param); } // Generate temporary file names for various certs $clear_file = tempnam($this->tmp_dir, 'clear_'); $signed_file = str_replace('clear', 'signed', $clear_file); $encrypted_file = str_replace('clear', 'encrypted', $clear_file); // Write our clear text file $out = fopen($clear_file, 'wb'); fwrite($out, $clear_text); fclose($out); // Sign our clear text file if (!openssl_pkcs7_sign($clear_file, $signed_file, $this->public_cert, $this->private_key, [], PKCS7_BINARY)) { throw new SecurityException('Unable to sign file'); } // Get back our signed file contents $signed_data = explode("\n\n", file_get_contents($signed_file)); // Write the signed file contents (part of them) $out = fopen($signed_file, 'wb'); fwrite($out, base64_decode($signed_data[1])); fclose($out); // Encrypt our signed file if (!openssl_pkcs7_encrypt($signed_file, $encrypted_file, $this->paypal_cert, [], PKCS7_BINARY)) { throw new SecurityException('Unable to encrypt file'); } // Get the encrypted data $encrypted_data = explode("\n\n", file_get_contents($encrypted_file)); $encrypted_text = $encrypted_data[1]; // Delete temporary files @unlink($clear_file); @unlink($signed_file); @unlink($encrypted_file); // Signature $encrypted_text = "-----BEGIN PKCS7-----\n" . $encrypted_text . "\n-----END PKCS7-----"; return $encrypted_text; }
/** * Encrypt a message in S/MIME format using a public key. * * @param string $text The text to be encrypted. * @param array $params The parameters needed for encryption. * <pre> * Parameters: * =========== * 'type' => 'message' (REQUIRED) * 'pubkey' => public key (REQUIRED) * </pre> * * @return string The encrypted message. * @throws Horde_Crypt_Exception */ protected function _encryptMessage($text, $params) { /* Check for required parameters. */ if (!isset($params['pubkey'])) { throw new Horde_Crypt_Exception(Horde_Crypt_Translation::t("A public S/MIME key is required to encrypt 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); /* Encrypt the document. */ $ciphers = array(OPENSSL_CIPHER_3DES, OPENSSL_CIPHER_DES, OPENSSL_CIPHER_RC2_128, OPENSSL_CIPHER_RC2_64, OPENSSL_CIPHER_RC2_40); foreach ($ciphers as $val) { if (openssl_pkcs7_encrypt($input, $output, $params['pubkey'], array(), 0, $val)) { $result = file_get_contents($output); if (!empty($result)) { return $this->_fixContentType($result, 'encrypt'); } } } throw new Horde_Crypt_Exception(Horde_Crypt_Translation::t("Could not S/MIME encrypt message.")); }
public function encryptx509($fin, $fout, $k, $o) { openssl_pkcs7_encrypt($fin, $fout, $k, $o); return $fout; }
function encryptButton($parameters) { // Check encryption data is available. if ($this->certificateID == '' || !isset($this->certificate) || !isset($this->paypalCertificate)) { return false; } $clearText = ''; $encryptedText = ''; if ($this->os == 'windows') { // initialize data. $data = "cert_id=" . $this->certificateID . "\n"; foreach ($parameters as $k => $v) { $d[] = "{$k}={$v}"; } $data .= join("\n", $d); $dataFile = tempnam($this->tempFileDirectory, 'data'); $out = fopen("{$dataFile}_data.txt", 'wb'); fwrite($out, $data); fclose($out); $out = fopen("{$dataFile}_signed.txt", "w+"); if (!openssl_pkcs7_sign("{$dataFile}_data.txt", "{$dataFile}_signed.txt", $this->certificate, $this->privateKey, array(), PKCS7_BINARY)) { return false; } fclose($out); $signedData = explode("\n\n", file_get_contents("{$dataFile}_signed.txt")); $out = fopen("{$dataFile}_signed.txt", 'wb'); fwrite($out, base64_decode($signedData[1])); fclose($out); if (!openssl_pkcs7_encrypt("{$dataFile}_signed.txt", "{$dataFile}_encrypted.txt", $this->paypalCertificate, array(), PKCS7_BINARY)) { return false; } $encryptedData = explode("\n\n", file_get_contents("{$dataFile}_encrypted.txt")); $encryptedText = $encryptedData[1]; @unlink($dataFile); @unlink("{$dataFile}_data.txt"); @unlink("{$dataFile}_signed.txt"); @unlink("{$dataFile}_encrypted.txt"); } else { // Compose clear text data. $clearText = 'cert_id=' . $this->certificateID; foreach (array_keys($parameters) as $key) { $clearText .= "\n{$key}={$parameters[$key]}"; } $clearFile = tempnam($this->tempFileDirectory, 'clear_'); $signedFile = preg_replace('/clear/', 'signed', $clearFile); $encryptedFile = preg_replace('/clear/', 'encrypted', $clearFile); $out = fopen($clearFile, 'wb'); fwrite($out, $clearText); fclose($out); if (!openssl_pkcs7_sign($clearFile, $signedFile, $this->certificate, $this->privateKey, array(), PKCS7_BINARY)) { return FALSE; } $signedData = explode("\n\n", file_get_contents($signedFile)); $out = fopen($signedFile, 'wb'); fwrite($out, base64_decode($signedData[1])); fclose($out); if (!openssl_pkcs7_encrypt($signedFile, $encryptedFile, $this->paypalCertificate, array(), PKCS7_BINARY)) { return FALSE; } $encryptedData = explode("\n\n", file_get_contents($encryptedFile)); $encryptedText = $encryptedData[1]; @unlink($clearFile); @unlink($signedFile); @unlink($encryptedFile); //return $clearText; } return $encryptedText; }
/** ---------------------------------------- /** Encrypt Button /** ----------------------------------------*/ function encrypt_data($params = array(), $type = 'button') { /** ----------------------------- /** Certificates, Keys, and TMP Files /** -----------------------------*/ $public_certificate = file_get_contents($this->public_certificate); $private_key = file_get_contents($this->private_key); $paypal_certificate = file_get_contents($this->paypal_certificate); $tmpin_file = tempnam($this->temp_path, 'paypal_'); $tmpout_file = tempnam($this->temp_path, 'paypal_'); $tmpfinal_file = tempnam($this->temp_path, 'paypal_'); /** ----------------------------- /** Prepare Our Data /** -----------------------------*/ $rawdata = ''; $params['cert_id'] = $this->certificate_id; foreach ($params as $name => $value) { $rawdata .= "{$name}={$value}\n"; } if (!($fp = fopen($tmpin_file, 'w'))) { exit('failure'); } fwrite($fp, rtrim($rawdata)); fclose($fp); /** ----------------------------- /** Sign Our File /** -----------------------------*/ if (!openssl_pkcs7_sign($tmpin_file, $tmpout_file, $public_certificate, $private_key, array(), PKCS7_BINARY)) { exit("Could not sign encrypted data: " . openssl_error_string()); } $data = explode("\n\n", file_get_contents($tmpout_file)); $data = base64_decode($data['1']); if (!($fp = fopen($tmpout_file, 'w'))) { exit("Could not open temporary file '{$tmpin_file}')"); } fwrite($fp, $data); fclose($fp); /** ----------------------------- /** Encrypt Our Data /** -----------------------------*/ if (!openssl_pkcs7_encrypt($tmpout_file, $tmpfinal_file, $paypal_certificate, array(), PKCS7_BINARY)) { exit("Could not encrypt data:" . openssl_error_string()); } $encdata = file_get_contents($tmpfinal_file, FALSE); if (empty($encdata)) { exit("Encryption and signature of data failed."); } $encdata = explode("\n\n", $encdata); $encdata = trim(str_replace("\n", '', $encdata['1'])); $encdata = "-----BEGIN PKCS7-----" . $encdata . "-----END PKCS7-----"; @unlink($tmpfinal_file); @unlink($tmpin_file); @unlink($tmpout_file); /** ----------------------------- /** Return The Encrypted Data String /** -----------------------------*/ return $encdata; }
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)) { echo "true\n"; unlink($outfile2); }
function process_button() { global $customer_id, $order, $languages_id, $currencies, $currency, $cart_PayPal_IPN_ID, $shipping; if (MODULE_PAYMENT_PAYPAL_IPN_CURRENCY == 'Selected Currency') { $my_currency = $currency; } else { $my_currency = substr(MODULE_PAYMENT_PAYPAL_IPN_CURRENCY, 5); } if (!in_array($my_currency, array('CAD', 'EUR', 'GBP', 'JPY', 'USD'))) { $my_currency = 'USD'; } $parameters = array(); if (MODULE_PAYMENT_PAYPAL_IPN_TRANSACTION_TYPE == 'Per Item' && MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS == 'False') { $parameters['cmd'] = '_cart'; $parameters['upload'] = '1'; for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { $item = $i + 1; $tax_value = $order->products[$i]['tax'] / 100 * $order->products[$i]['final_price']; $parameters['item_name_' . $item] = $order->products[$i]['name']; $parameters['amount_' . $item] = number_format($order->products[$i]['final_price'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $parameters['tax_' . $item] = number_format($tax_value * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $parameters['quantity_' . $item] = $order->products[$i]['qty']; if ($i == 0) { if (DISPLAY_PRICE_WITH_TAX == 'true') { $shipping_cost = $order->info['shipping_cost']; } else { $module = substr($shipping['id'], 0, strpos($shipping['id'], '_')); $shipping_tax = tep_get_tax_rate($GLOBALS[$module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']); $shipping_cost = $order->info['shipping_cost'] + tep_calculate_tax($order->info['shipping_cost'], $shipping_tax); } $parameters['shipping_' . $item] = number_format($shipping_cost * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } if (isset($order->products[$i]['attributes'])) { for ($j = 0, $n2 = sizeof($order->products[$i]['attributes']); $j < $n2; $j++) { if (DOWNLOAD_ENABLED == 'true') { $attributes_query = "select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename\r\n from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa\r\n left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\r\n on pa.products_attributes_id=pad.products_attributes_id\r\n where pa.products_id = '" . $order->products[$i]['id'] . "'\r\n and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "'\r\n and pa.options_id = popt.products_options_id\r\n and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "'\r\n and pa.options_values_id = poval.products_options_values_id\r\n and popt.language_id = '" . $languages_id . "'\r\n and poval.language_id = '" . $languages_id . "'"; $attributes = tep_db_query($attributes_query); } else { $attributes = tep_db_query("select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . $order->products[$i]['id'] . "' and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . $languages_id . "' and poval.language_id = '" . $languages_id . "'"); } $attributes_values = tep_db_fetch_array($attributes); // Unfortunately PayPal only accepts two attributes per product, so the // third attribute onwards will not be shown at PayPal $parameters['on' . $j . '_' . $item] = $attributes_values['products_options_name']; $parameters['os' . $j . '_' . $item] = $attributes_values['products_options_values_name']; } } } $parameters['num_cart_items'] = $item; } else { $parameters['cmd'] = '_xclick'; $parameters['item_name'] = STORE_NAME; $parameters['shipping'] = number_format($order->info['shipping_cost'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $parameters['tax'] = number_format($order->info['tax'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } $parameters['business'] = MODULE_PAYMENT_PAYPAL_IPN_ID; $parameters['amount'] = number_format(($order->info['total'] - $order->info['shipping_cost'] - $order->info['tax']) * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $parameters['currency_code'] = $my_currency; $parameters['invoice'] = substr($cart_PayPal_IPN_ID, strpos($cart_PayPal_IPN_ID, '-') + 1); $parameters['custom'] = $customer_id; $parameters['no_shipping'] = '1'; $parameters['no_note'] = '1'; $parameters['notify_url'] = tep_href_link('ext/modules/payment/paypal_ipn/ipn.php', '', 'SSL', false, false); $parameters['return'] = tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'); $parameters['cancel_return'] = tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'); $parameters['bn'] = $this->identifier; if (tep_not_null(MODULE_PAYMENT_PAYPAL_IPN_PAGE_STYLE)) { $parameters['page_style'] = MODULE_PAYMENT_PAYPAL_IPN_PAGE_STYLE; } if (MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS == 'True') { $parameters['cert_id'] = MODULE_PAYMENT_PAYPAL_IPN_EWP_CERT_ID; $random_string = rand(100000, 999999) . '-' . $customer_id . '-'; $data = ''; while (list($key, $value) = each($parameters)) { $data .= $key . '=' . $value . "\n"; } $fp = fopen(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', 'w'); fwrite($fp, $data); fclose($fp); unset($data); if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) { openssl_pkcs7_sign(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_IPN_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); // remove headers from the signature $signed = file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $signed = explode("\n\n", $signed); $signed = base64_decode($signed[1]); $fp = fopen(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', 'w'); fwrite($fp, $signed); fclose($fp); unset($signed); openssl_pkcs7_encrypt(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_IPN_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); // remove headers from the encrypted result $data = file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); $data = explode("\n\n", $data); $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----'; unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } else { exec(MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL . ' smime -sign -in ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); exec(MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY . ' < ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt > ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $fh = fopen(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', 'rb'); $data = fread($fh, filesize(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt')); fclose($fh); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } $process_button_string = tep_draw_hidden_field('cmd', '_s-xclick') . tep_draw_hidden_field('encrypted', $data); unset($data); } else { while (list($key, $value) = each($parameters)) { echo tep_draw_hidden_field($key, $value); } } return $process_button_string; }
/** * Compute public encryption key */ protected function generatePublicEncryptionKey() { $keybytelen = $this->encryptdata['Length'] / 8; // random 20-byte seed $seed = sha1($this->encrypt('seed'), true); $recipient_bytes = ''; foreach ($this->encryptdata['pubkeys'] as $pubkey) { // for each public certificate if (isset($pubkey['p'])) { $pkprotection = $this->getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']); } else { $pkprotection = $this->encryptdata['protection']; } // get default permissions (reverse byte order) $pkpermissions = $this->getEncPermissionsString($pkprotection); // envelope data $envelope = $seed . $pkpermissions; // write the envelope data to a temporary file $tempkeyfile = tempnam(sys_get_temp_dir(), '__tcpdf_key_' . md5($this->encryptdata['fileid'] . $envelope) . '_'); if (file_put_contents($tempkeyfile, $envelope) === false) { // @codeCoverageIgnoreStart throw new EncException('Unable to create temporary key file: ' . $tempkeyfile); // @codeCoverageIgnoreEnd } $tempencfile = tempnam(sys_get_temp_dir(), '__tcpdf_enc_' . md5($this->encryptdata['fileid'] . $envelope) . '_'); if (!function_exists('openssl_pkcs7_encrypt') || !openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, file_get_contents($pubkey['c']), array(), PKCS7_BINARY | PKCS7_DETACHED)) { throw new EncException('Unable to encrypt the file: ' . $tempkeyfile . "\n" . 'Public-Key Security requires openssl_pkcs7_encrypt.'); } // read encryption signature $signature = file_get_contents($tempencfile); // extract signature $signature = substr($signature, strpos($signature, 'Content-Disposition')); $tmparr = explode("\n\n", $signature); $signature = trim($tmparr[1]); unset($tmparr); // decode signature $signature = base64_decode($signature); // convert signature to hex $hexsignature = current(unpack('H*', $signature)); // store signature on recipients array $this->encryptdata['Recipients'][] = $hexsignature; // The bytes of each item in the Recipients array of PKCS#7 objects // in the order in which they appear in the array $recipient_bytes .= $signature; } // calculate encryption key if ($this->encryptdata['mode'] == 3) { // AES-256 $this->encryptdata['key'] = substr(hash('sha256', $seed . $recipient_bytes, true), 0, $keybytelen); } else { // RC4-40, RC4-128, AES-128 $this->encryptdata['key'] = substr(sha1($seed . $recipient_bytes, true), 0, $keybytelen); } }
/** * Encrypts and signs the request to paypal * * To generate a keypair: * openssl genrsa -des3 -out privkey.pem 2048 * openssl req -new -x509 -key privkey.pem -out cacert.pem -days 3650 * * To encrypt and sign (that's what we do here): * openssl smime -sign -signer cacert.pem -inkey privkey.pem -outform der -nodetach -binary -passin pass:1234 | openssl smime -encrypt -des3 -binary -outform pem paypal_cert_pem.txt * * @param string $cleartext Cleartext to encrypt and sign * @return string Encrypted text or FALSE */ private function _paypalEncrypt( $cleartext ) { $return = false; $paypal_openssl_path = $this->params->get( 'openssl_exec_path', '/usr/bin/openssl' ); $paypal_public_certificate_path = $this->getAccountParam( 'paypal_public_certificate_path' ); $paypal_private_key_path = $this->getAccountParam( 'paypal_private_key_path' ); $paypal_public_key_path = $this->getAccountParam( 'paypal_public_key_path' ); $paypal_private_key_password = $this->getAccountParam( 'paypal_private_key_password' ); $tmpDir = $this->findATmpDir(); if ( ( $tmpDir === null ) || ( ! is_dir( $tmpDir ) ) || ! is_writable( $tmpDir ) ) { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl', 'did not find a writable temporary directory (' . $tmpDir . '). Please make sure that your cachepath global CMS setting is a writable directory.' ); $tmpDir = null; } $h = @getenv('HOME') . "\n"; if ( ! is_writable( $h ) ) { @putenv("HOME=/tmp"); // try avoiding unable to write 'random state' ( http://www.paypaldeveloper.com/pdn/board/message?board.id=ewp&thread.id=110&view=by_date_ascending&page=2 ) } else { $h = null; } if ( extension_loaded( 'openssl' ) && defined( 'OPENSSL_VERSION_TEXT' ) && ( $tmpDir !== null ) ) { $clearFile = tempnam($tmpDir, 'clr_'); $signedFile = tempnam($tmpDir, 'sign_'); $encryptedFile = tempnam($tmpDir, 'encr_'); if ( is_readable( $paypal_public_key_path ) && is_readable( $paypal_private_key_path ) && is_readable( $paypal_public_certificate_path ) ) { $certificate = openssl_x509_read( file_get_contents( $paypal_public_key_path ) ); $privateKey = openssl_pkey_get_private( file_get_contents( $paypal_private_key_path ), $paypal_private_key_password ); $paypalcert = openssl_x509_read( file_get_contents( $paypal_public_certificate_path ) ); if ( ( $certificate !== false ) && ( $privateKey !== false ) && ( $paypalcert !== false ) ) { $privOk = openssl_x509_check_private_key( $certificate, $privateKey ); if ( $privOk ) { $out = fopen( $clearFile, 'wb' ); if ( $out !== false ) { fwrite( $out, $cleartext ); fclose( $out ); if ( openssl_pkcs7_sign( $clearFile, $signedFile, $certificate, $privateKey, array(), PKCS7_BINARY ) ) { @unlink( $clearFile ); $signedData = explode( "\n\n", file_get_contents( $signedFile ) ); $out = fopen($signedFile, 'wb'); if ( $out !== false ) { fwrite( $out, base64_decode( $signedData[1] ) ); fclose( $out ); if ( openssl_pkcs7_encrypt( $signedFile, $encryptedFile, $paypalcert, array(), PKCS7_BINARY ) ) { @unlink( $signedFile ); $encryptedData = explode("\n\n", file_get_contents( $encryptedFile ), 2 ); @unlink( $encryptedFile ); $return = "-----BEGIN PKCS7-----\n" . trim( $encryptedData[1] ) . "\n-----END PKCS7-----"; } else { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_encrypt(signedFile,paypal_public_cer) ', 'returns an error on signature.' ); } } else { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl open ', $signedFile . ' returns an error creating it.' ); } } else { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_sign(message,your_private_key)', 'returns an error.' ); } } else { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl open ', $clearFile . ' returns an error creating it.' ); } } else { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_sign(message,your_private_key)', 'returns an error.' ); } } else { if ( $certificate === false ) { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_x509_read(your_public_key)', 'returns an error.' ); } if ( $privateKey === false ) { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkey_get_private(your_private_key)', 'returns an error. Maybe wrong password for private key ?' ); } if ( $paypalcert === false ) { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_x509_read(paypal_public_certificate)', 'returns an error.' ); } } } else { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl tempnam()', 'returns unwritable filepaths (' . $clearFile . ')' ); } } if ( $return === false ) { if ( function_exists( 'is_executable' ) ) { $configPath = $this->params->get( 'openssl_exec_path', '/usr/bin/openssl' ); $paths = array( '/usr/bin/openssl', '/usr/local/bin/openssl', 'openssl' ); if ( $configPath ) { array_unshift( $paths, $configPath ); } foreach ($paths as $path) { if ( @is_executable( $path ) ) { // openssl found: $paypal_openssl_path = $path; break; } } } if ( @is_executable( $paypal_openssl_path ) ) { $openssl_cmd = $paypal_openssl_path . ' smime -sign -signer ' .$paypal_public_key_path . ' -inkey ' . $paypal_private_key_path . ' -outform der -nodetach -binary -passin pass:'******' | ' . $paypal_openssl_path . ' smime -encrypt -des3 -binary -outform pem ' . $paypal_public_certificate_path; $descriptors = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w') ); $pipes = null; $process = @proc_open( $openssl_cmd, $descriptors, $pipes ); // PHP 4.3.0 required for paypal encryption ! if (is_resource($process)) { @fwrite( $pipes[0], $cleartext ); @fflush( $pipes[0] ); @fclose( $pipes[0] ); $output = ''; while ( ! feof( $pipes[1] ) ) { $output .= @fgets( $pipes[1] ); } $error = ''; while ( ! feof( $pipes[2] ) ) { $error .= @fgets( $pipes[2] ); } $error = trim( $error ); @fclose( $pipes[1] ); @fclose( $pipes[2] ); @proc_close( $process ); if ( $error ) { $this->_setLogErrorMSG( 3, $this->account, 'paypal openssl executable error', $error ); } $return = trim( $output ); } else { $this->_setLogErrorMSG( 5, $this->account, 'paypal openssl executable', 'could not start with proc_open' ); } } } if ( $h ) { @putenv( "HOME=" . $h ); } return $return; }
function encrypt($certificate_id) { # since this is a shared class, but certs are site-specific, go through include_paths to find realpath foreach (explode(':', ini_get('include_path')) as $path) { if (file_exists($path . '/paypal/paypal.cert')) { $public_file = realpath($path . '/paypal/public.cert'); $private_file = realpath($path . '/paypal/private.cert'); $paypal_file = realpath($path . '/paypal/paypal.cert'); $public_cert = openssl_x509_read(file_get_contents($public_file)); $private_cert = openssl_get_privatekey(file_get_contents($private_file)); if (openssl_x509_check_private_key($public_cert, $private_cert) === false) { return false; } $paypal_cert = openssl_x509_read(file_get_contents($paypal_file)); break; } } $clear_text = 'cert_id=' . $certificate_id; foreach ($this->postvars() as $k => $v) { $clear_text .= "\n" . $k . '=' . $v; } $clear_file = tempnam('/tmp/', 'clear_'); # alt: sys_get_temp_dir() $signed_file = preg_replace('/clear/', 'signed', $clear_file); $encrypted_file = preg_replace('/clear/', 'encrypted', $clear_file); file_put_contents($clear_file, $clear_text); if (!openssl_pkcs7_sign($clear_file, $signed_file, $public_cert, $private_cert, array(), PKCS7_BINARY)) { return false; } list($x, $signed_text) = explode("\n\n", file_get_contents($signed_file)); #? file_put_contents($signed_file, base64_decode($signed_text)); if (!openssl_pkcs7_encrypt($signed_file, $encrypted_file, $paypal_cert, array(), PKCS7_BINARY)) { return false; } list($x, $encrypted_text) = explode("\n\n", file_get_contents($encrypted_file)); #? $this->encrypted = "\n-----BEGIN PKCS7-----\n{$encrypted_text}\n-----END PKCS7-----\n"; @unlink($clear_file); @unlink($signed_file); @unlink($encrypted_file); }
function process_button() { global $customer_id, $order, $languages_id, $currencies, $currency, $cart_PayPal_IPN_ID, $shipping, $order_total_modules; if (MODULE_PAYMENT_PAYPAL_IPN_CURRENCY == 'Selected Currency') { $my_currency = $currency; } else { $my_currency = substr(MODULE_PAYMENT_PAYPAL_IPN_CURRENCY, 5); } if (!in_array($my_currency, array('AUD', 'CAD', 'CHF', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HUF', 'JPY', 'NOK', 'NZD', 'PLN', 'SEK', 'SGD', 'USD'))) { $my_currency = 'USD'; } // BOF Per Item mode fix by alexstudio $order_totals = array(); if (is_array($order_total_modules->modules)) { reset($order_total_modules->modules); while (list(, $value) = each($order_total_modules->modules)) { $class = substr($value, 0, strrpos($value, '.')); if ($GLOBALS[$class]->enabled) { for ($i = 0, $n = sizeof($GLOBALS[$class]->output); $i < $n; $i++) { if (tep_not_null($GLOBALS[$class]->output[$i]['title']) && tep_not_null($GLOBALS[$class]->output[$i]['text'])) { $order_totals[] = array('code' => $GLOBALS[$class]->code, 'title' => $GLOBALS[$class]->output[$i]['title'], 'text' => $GLOBALS[$class]->output[$i]['text'], 'value' => $GLOBALS[$class]->output[$i]['value'], 'sort_order' => $GLOBALS[$class]->sort_order); } } } } } foreach ($order_totals as $ot) { $order_total[$ot['code']] = $ot['value']; } $subtotal = $order_total['ot_subtotal']; if (DISPLAY_PRICE_WITH_TAX == 'true') { $subtotal -= $order->info['tax']; } // EOF Per Item mode fix by alexstudio $parameters = array(); if (MODULE_PAYMENT_PAYPAL_IPN_TRANSACTION_TYPE == 'Per Item') { $parameters['cmd'] = '_cart'; $parameters['upload'] = '1'; // Decide how many items are virtual (no shipping) $shipping_count = 0; $shipping_added = 0; $handling_added = 0; $item_tax = 0; $virtual_items = 0; for ($y = 0; $y < sizeof($order->products); $y++) { if (is_array($order->products[$y]['attributes'])) { while (list($key, $value) = each($order->products[$y]['attributes'])) { $z = $key; $attributes_query = "select pad.products_attributes_filename\n from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval,\n " . TABLE_PRODUCTS_ATTRIBUTES . " pa left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\n on pa.products_attributes_id=pad.products_attributes_id\n where pa.products_id = '" . $order->products[$y]['id'] . "'\n and pa.options_id = '" . $order->products[$y]['attributes'][$z]['option_id'] . "'\n and pa.options_id = popt.products_options_id\n and pa.options_values_id = '" . $order->products[$y]['attributes'][$z]['value_id'] . "'\n and pa.options_values_id = poval.products_options_values_id"; $attributes = tep_db_query($attributes_query); $attributes_values = tep_db_fetch_array($attributes); if (tep_not_null($attributes_values['products_attributes_filename'])) { $virtual_items++; } } } } for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { $item = $i + 1; $tax_value = $order->products[$i]['tax'] / 100 * $order->products[$i]['final_price']; $parameters['item_name_' . $item] = $order->products[$i]['name']; $parameters['item_number_' . $item] = $order->products[$i]['model']; // BOF Tax pre item fix by AlexStudio if (MOVE_TAX_TO_TOTAL_AMOUNT == 'True') { $parameters['amount_' . $item] = number_format(($order->products[$i]['final_price'] + $tax_value) * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } else { $parameters['amount_' . $item] = number_format($order->products[$i]['final_price'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $parameters['tax_' . $item] = number_format($tax_value * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } $item_tax += number_format($tax_value * $order->products[$i]['qty'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); // EOF Tax pre item fix by AlexStudio $parameters['quantity_' . $item] = $order->products[$i]['qty']; // BOF shipping & handling fix by AlexStudio $item_has_shipping = true; // EOF shipping & handling fix by AlexStudio if (isset($order->products[$i]['attributes'])) { for ($j = 0, $n2 = sizeof($order->products[$i]['attributes']); $j < $n2; $j++) { if (DOWNLOAD_ENABLED == 'true') { $attributes_query = "select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix, pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename\n from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa\n left join " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad\n on pa.products_attributes_id=pad.products_attributes_id\n where pa.products_id = '" . $order->products[$i]['id'] . "'\n and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "'\n and pa.options_id = popt.products_options_id\n and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "'\n and pa.options_values_id = poval.products_options_values_id\n and popt.language_id = '" . $languages_id . "'\n and poval.language_id = '" . $languages_id . "'"; $attributes = tep_db_query($attributes_query); } else { $attributes = tep_db_query("select popt.products_options_name, poval.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . $order->products[$i]['id'] . "' and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . $languages_id . "' and poval.language_id = '" . $languages_id . "'"); } $attributes_values = tep_db_fetch_array($attributes); // BOF shipping & handling fix by AlexStudio if (tep_not_null($attributes_values['products_attributes_filename'])) { $item_has_shipping = false; } // EOF shipping & handling fix by AlexStudio // Unfortunately PayPal only accepts two attributes per product, so the // third attribute onwards will not be shown at PayPal $parameters['on' . $j . '_' . $item] = $attributes_values['products_options_name']; $parameters['os' . $j . '_' . $item] = $attributes_values['products_options_values_name']; } } // BOF shipping & handling fix by AlexStudio $handling = $order_total['ot_loworderfee']; if ($n == 1 || $item < $n) { $parameters['handling_' . $item] = number_format($handling / $n * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $handling_added += $parameters['handling_' . $item]; } else { $parameters['handling_' . $item] = number_format($handling * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)) - $handling_added; } if ($item_has_shipping) { $shipping_count++; $shipping_items = $n - $virtual_items; if ($shipping_items == 1 || $shipping_count < $shipping_items) { $parameters['shipping_' . $item] = number_format($order_total['ot_shipping'] / $shipping_items * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $shipping_added += $parameters['shipping_' . $item]; } else { $parameters['shipping_' . $item] = number_format($order_total['ot_shipping'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)) - $shipping_added; } } // EOF shipping & handling fix by AlexStudio } // BOF Tax pre item fix by AlexStudio $tax_total = number_format($order->info['tax'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); if ($tax_total > $item_tax && DISPLAY_PRICE_WITH_TAX != 'true') { $item++; $parameters['item_name_' . $item] = 'Shipping Tax'; $parameters['amount_' . $item] = $tax_total - $item_tax; $parameters['quantity_' . $item] = 1; } // EOF Tax pre item fix by AlexStudio if (MOVE_TAX_TO_TOTAL_AMOUNT == 'True') { // BOF Tax pre item fix by AlexStudio $parameters['amount'] = number_format(($subtotal + $order->info['tax']) * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } else { // default $parameters['amount'] = number_format($subtotal * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); // EOF Tax pre item fix by AlexStudio } } else { $parameters['cmd'] = '_ext-enter'; $parameters['redirect_cmd'] = '_xclick'; $parameters['item_name'] = STORE_NAME; ///CCGV extras by Alexander Dimelow - better to calculate separate otherwise the shipping Free vaucher/code never will work $shipping['cost'] = number_format($order_total['ot_shipping'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); // BOF shipping & handling fix by AlexStudio if (MOVE_TAX_TO_TOTAL_AMOUNT == 'True') { ///CCGV extras by Alexander Dimelow if (isset($order_total['ot_gv']) || isset($order_total['ot_coupon'])) { $parameters['amount'] = number_format(($subtotal + $order->info['tax']) * $currencies->get_value($my_currency) - $order_total['ot_gv'] - $order_total['ot_coupon'], $currencies->get_decimal_places($my_currency)); } else { $parameters['amount'] = number_format(($subtotal + $order->info['tax']) * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } } else { // default $parameters['amount'] = number_format($subtotal * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); $parameters['tax'] = number_format($order->info['tax'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } if ($order->content_type != 'virtual') { $parameters['shipping'] = number_format($order_total['ot_shipping'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); } $parameters['handling'] = number_format($order_total['ot_loworderfee'] * $currencies->get_value($my_currency), $currencies->get_decimal_places($my_currency)); // EOF shipping & handling fix by AlexStudio } // BOF billing address fix by AlexStudio if ($order->content_type != 'virtual') { $state_abbr = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], $order->delivery['state']); } else { $state_abbr = tep_get_zone_code($order->billing['country']['id'], $order->billing['zone_id'], $order->billing['state']); } // EOF billing address fix by AlexStudio $parameters['business'] = MODULE_PAYMENT_PAYPAL_IPN_ID; // let's check what has been defined in the shop admin for the shipping address // BOF parameters fix by AlexStudio if ($order->content_type != 'virtual') { $parameters['address_override'] = '1'; $parameters['no_shipping'] = '2'; $parameters['night_phone_b'] = $order->customer['telephone']; $parameters['first_name'] = $order->delivery['firstname']; $parameters['last_name'] = $order->delivery['lastname']; $parameters['address1'] = $order->delivery['street_address']; $parameters['address2'] = $order->delivery['suburb']; $parameters['city'] = $order->delivery['city']; $parameters['zip'] = $order->delivery['postcode']; $parameters['state'] = $state_abbr; $parameters['country'] = $order->delivery['country']['iso_code_2']; $parameters['email'] = $order->customer['email_address']; } else { $parameters['no_shipping'] = '1'; $parameters['night_phone_b'] = $order->customer['telephone']; $parameters['first_name'] = $order->billing['firstname']; $parameters['last_name'] = $order->billing['lastname']; $parameters['address1'] = $order->billing['street_address']; $parameters['address2'] = $order->billing['suburb']; $parameters['city'] = $order->billing['city']; $parameters['zip'] = $order->billing['postcode']; $parameters['state'] = $state_abbr; $parameters['country'] = $order->billing['country']['iso_code_2']; $parameters['email'] = $order->customer['email_address']; } /********************************************************************************************* * Currently these are the supported charsets: * * big5, euc-jp, euc-kr, euc-tw, gb2312, hz-gb-2312, ibm-862, iso-2022-cn, iso-2022-jp, * * iso-2022-kr, iso-8859-1, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, * * iso-8859-7, iso-8859-8, iso-8859-9, iso-8859-13, iso-8859-15, ko18-r, shift_jis, * * utf-7, utf-8, utf-16, utf-16be, utf-16le, utf-16_platformendian, utf-16_oppositeendian, * * utf-32, utf-32be, utf-32le, utf-32_platformendian, utf-32_oppositeendian, usa-ascii, * * windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, * * windows-1256, windows-1257, windows-1258, windows-874, windows-949, x-mac-greek, * * x-mac-turkish, x-mac-centraleurroman, x-mac-cyrillic, ebcdic-cp-us, ibm-1047 * **********************************************************************************************/ $parameters['charset'] = "utf-8"; // Modify this line if you have problems with the character set. // EOF parameters fix by AlexStudio $parameters['currency_code'] = $my_currency; $parameters['invoice'] = substr($cart_PayPal_IPN_ID, strpos($cart_PayPal_IPN_ID, '-') + 1); $parameters['custom'] = $customer_id; $parameters['no_note'] = '1'; $parameters['notify_url'] = tep_href_link('ext/modules/payment/paypal_ipn/ipn.php', 'language=' . $_SESSION['language'], 'SSL', false, false); $parameters['cbt'] = CONFIRMATION_BUTTON_TEXT; $parameters['return'] = tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'); // $parameters['cancel_return'] = tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'); $parameters['cancel_return'] = tep_href_link(FILENAME_SHOPPING_CART, 'ipn=cancel_ipn&order=' . $parameters['invoice'], 'SSL'); $parameters['bn'] = $this->identifier; $parameters['lc'] = $order->customer['country']['iso_code_2']; if (tep_not_null(MODULE_PAYMENT_PAYPAL_IPN_PAGE_STYLE)) { $parameters['page_style'] = MODULE_PAYMENT_PAYPAL_IPN_PAGE_STYLE; } if (MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS == 'True') { $parameters['cert_id'] = MODULE_PAYMENT_PAYPAL_IPN_EWP_CERT_ID; $random_string = rand(100000, 999999) . '-' . $customer_id . '-'; $data = ''; reset($parameters); while (list($key, $value) = each($parameters)) { $data .= $key . '=' . $value . "\n"; } $fp = fopen(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', 'w'); fwrite($fp, $data); fclose($fp); unset($data); if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) { openssl_pkcs7_sign(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_IPN_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); // remove headers from the signature $signed = file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $signed = explode("\n\n", $signed); $signed = base64_decode($signed[1]); $fp = fopen(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', 'w'); fwrite($fp, $signed); fclose($fp); unset($signed); openssl_pkcs7_encrypt(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_IPN_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); // remove headers from the encrypted result $data = file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); $data = explode("\n\n", $data); $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----'; unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } else { exec(MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL . ' smime -sign -in ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); exec(MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY . ' < ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt > ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $fh = fopen(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', 'rb'); $data = fread($fh, filesize(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt')); fclose($fh); unlink(MODULE_PAYMENT_PAYPAL_IPN_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } $process_button_string = tep_draw_hidden_field('cmd', '_s-xclick') . tep_draw_hidden_field('encrypted', $data); unset($data); } else { reset($parameters); while (list($key, $value) = each($parameters)) { $process_button_string .= tep_draw_hidden_field($key, $value); } } return $process_button_string; }
/** * Compute encryption key * @protected * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ protected function _generateencryptionkey() { $keybytelen = $this->encryptdata['Length'] / 8; if (!$this->encryptdata['pubkey']) { // standard mode if ($this->encryptdata['mode'] == 3) { // AES-256 // generate 256 bit random key $this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen); // truncate passwords $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']); $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']); // Compute U value $this->encryptdata['U'] = $this->_Uvalue(); // Compute UE value $this->encryptdata['UE'] = $this->_UEvalue(); // Compute O value $this->encryptdata['O'] = $this->_Ovalue(); // Compute OE value $this->encryptdata['OE'] = $this->_OEvalue(); // Compute P value $this->encryptdata['P'] = $this->encryptdata['protection']; // Computing the encryption dictionary's Perms (permissions) value $perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3 $perms .= chr(255) . chr(255) . chr(255) . chr(255); // bytes 4-7 if (isset($this->encryptdata['CF']['EncryptMetadata']) and !$this->encryptdata['CF']['EncryptMetadata']) { // byte 8 $perms .= 'F'; } else { $perms .= 'T'; } $perms .= 'adb'; // bytes 9-11 $perms .= 'nick'; // bytes 12-15 $iv = str_repeat("", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB)); $this->encryptdata['perms'] = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->encryptdata['key'], $perms, MCRYPT_MODE_ECB, $iv); } else { // RC4-40, RC4-128, AES-128 // Pad passwords $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'] . TCPDF_STATIC::$enc_padding, 0, 32); $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'] . TCPDF_STATIC::$enc_padding, 0, 32); // Compute O value $this->encryptdata['O'] = $this->_Ovalue(); // get default permissions (reverse byte order) $permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // Compute encryption key $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'] . $this->encryptdata['O'] . $permissions . $this->encryptdata['fileid']); if ($this->encryptdata['mode'] > 0) { for ($i = 0; $i < 50; ++$i) { $tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen)); } } $this->encryptdata['key'] = substr($tmp, 0, $keybytelen); // Compute U value $this->encryptdata['U'] = $this->_Uvalue(); // Compute P value $this->encryptdata['P'] = $this->encryptdata['protection']; } } else { // Public-Key mode // random 20-byte seed $seed = sha1(TCPDF_STATIC::getRandomSeed(), true); $recipient_bytes = ''; foreach ($this->encryptdata['pubkeys'] as $pubkey) { // for each public certificate if (isset($pubkey['p'])) { $pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']); } else { $pkprotection = $this->encryptdata['protection']; } // get default permissions (reverse byte order) $pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection); // envelope data $envelope = $seed . $pkpermissions; // write the envelope data to a temporary file $tempkeyfile = TCPDF_STATIC::getObjFilename('tmpkey'); $f = fopen($tempkeyfile, 'wb'); if (!$f) { $this->Error('Unable to create temporary key file: ' . $tempkeyfile); } $envelope_length = strlen($envelope); fwrite($f, $envelope, $envelope_length); fclose($f); $tempencfile = TCPDF_STATIC::getObjFilename('tmpenc'); if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) { $this->Error('Unable to encrypt the file: ' . $tempkeyfile); } unlink($tempkeyfile); // read encryption signature $signature = file_get_contents($tempencfile, false, null, $envelope_length); unlink($tempencfile); // extract signature $signature = substr($signature, strpos($signature, 'Content-Disposition')); $tmparr = explode("\n\n", $signature); $signature = trim($tmparr[1]); unset($tmparr); // decode signature $signature = base64_decode($signature); // convert signature to hex $hexsignature = current(unpack('H*', $signature)); // store signature on recipients array $this->encryptdata['Recipients'][] = $hexsignature; // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array $recipient_bytes .= $signature; } // calculate encryption key if ($this->encryptdata['mode'] == 3) { // AES-256 $this->encryptdata['key'] = substr(hash('sha256', $seed . $recipient_bytes, true), 0, $keybytelen); } else { // RC4-40, RC4-128, AES-128 $this->encryptdata['key'] = substr(sha1($seed . $recipient_bytes, true), 0, $keybytelen); } } }
/** * Creates a new encrypted button HTML block * * @param array The button parameters as key/value pairs * @return mixed A string of HTML or a Paypal error object on failure */ function encryptButton($buttonParams) { if (!is_object($this->_profile)) { return PayPal::raiseError("No Profile is set, cannot encrypt"); } $res = $this->_profile->validate(); if (PayPal::isError($res)) { return $res; } $merchant_cert = 'file://' . $this->_profile->getCertificateFile(); $merchant_key = 'file://' . $this->_profile->getPrivateKeyFile(); $enc_cert = 'file://' . $this->getPayPalCertificateFile($this->_profile->getEnvironment()); $tmpin_file = tempnam('/tmp', 'paypal_'); $tmpout_file = tempnam('/tmp', 'paypal_'); $tmpfinal_file = tempnam('/tmp', 'paypal_'); $rawdata = array(); $buttonParams['cert_id'] = $this->_profile->getCertificateId(); foreach ($buttonParams as $name => $value) { $rawdata[] = "{$name}={$value}"; } $rawdata = implode("\n", $rawdata); $fp = fopen($tmpin_file, 'w'); if (!$fp) { return PayPal::raiseError("Could not open temporary file '{$tmpin_file}')"); } fwrite($fp, $rawdata); fclose($fp); if (!@openssl_pkcs7_sign($tmpin_file, $tmpout_file, $merchant_cert, array($merchant_key, $this->_profile->getPrivateKeyPassword()), array(), PKCS7_BINARY)) { return PayPal::raiseError("Could not sign encrypted data: " . openssl_error_string()); } $data = file_get_contents($tmpout_file); $data = explode("\n\n", $data); $data = $data[1]; $data = base64_decode($data); $fp = fopen($tmpout_file, 'w'); if (!$fp) { return PayPal::raiseError("Could not open temporary file '{$tmpin_file}')"); } fwrite($fp, $data); fclose($fp); if (!@openssl_pkcs7_encrypt($tmpout_file, $tmpfinal_file, $enc_cert, array(), PKCS7_BINARY)) { return PayPal::raiseError("Could not encrypt data:" . openssl_error_string()); } $encdata = @file_get_contents($tmpfinal_file, false); if (!$encdata) { return PayPal::raiseError("Encryption and signature of data failed."); } $encdata = explode("\n\n", $encdata); $encdata = trim(str_replace("\n", '', $encdata[1])); $encdata = "-----BEGIN PKCS7-----{$encdata}-----END PKCS7-----"; @unlink($tmpfinal_file); @unlink($tmpin_file); @unlink($tmpout_file); $action = $this->_profile->getUrl(); $buttonimgurl = $this->_profile->getButtonImage(); $retval = <<<PPHTML <FORM ACTION="{$action}" METHOD="post"> <INPUT TYPE="hidden" NAME="cmd" VALUE="_s-xclick"> <INPUT TYPE="hidden" NAME="encrypted" VALUE="{$encdata}"> <INPUT TYPE="image" SRC="{$buttonimgurl}" BORDER="0" NAME="submit" ALT="Make Payments with PayPal -- it's fast, free and secure!"> </FORM> PPHTML; return $retval; }
/** * Using the previously set certificates and the tempFileDirectory to * encrypt the button information * * @param array $parameters Array with parameter names as keys * @return mixed The encrypted string OR false */ function encryptButton($parameters) { if ($this->certificateID == '' or !isset($this->certificate) or !isset($this->paypalCertificate)) { return false; } $clearText = ''; $encryptedText = ''; $data = "cert_id=" . $this->certificateID . "\n"; foreach ($parameters as $k => $v) { $d[] = "{$k}={$v}"; } $data .= join("\n", $d); $dataFile = tempnam($this->tempFileDirectory, 'data'); $out = fopen("{$dataFile}_data.txt", 'wb'); fwrite($out, $data); fclose($out); $out = fopen("{$dataFile}_signed.txt", "w+"); if (!openssl_pkcs7_sign("{$dataFile}_data.txt", "{$dataFile}_signed.txt", $this->certificate, $this->privateKey, array(), PKCS7_BINARY)) { $this->error = 4; return false; } fclose($out); $signedData = explode("\n\n", file_get_contents("{$dataFile}_signed.txt")); $out = fopen("{$dataFile}_signed.txt", 'wb'); fwrite($out, base64_decode($signedData[1])); fclose($out); if (!openssl_pkcs7_encrypt("{$dataFile}_signed.txt", "{$dataFile}_encrypted.txt", $this->paypalCertificate, array(), PKCS7_BINARY)) { $this->error = 4; return false; } $encryptedData = explode("\n\n", file_get_contents("{$dataFile}_encrypted.txt")); $encryptedText = $encryptedData[1]; @unlink($dataFile); @unlink("{$dataFile}_data.txt"); @unlink("{$dataFile}_signed.txt"); @unlink("{$dataFile}_encrypted.txt"); return "-----BEGIN PKCS7-----\n" . $encryptedText . "\n-----END PKCS7-----"; }
/** * Takes the body of the message and processes it with S/MIME * * @param string $to The recipients being sent to * @param string $subject The subject of the email * @param string $headers The headers for the message * @param string $body The message body * @return array `0` => The message headers, `1` => The message body */ private function createSMIMEBody($to, $subject, $headers, $body) { if (!$this->smime_encrypt && !$this->smime_sign) { return array($headers, $body); } $plaintext_file = tempnam('', '__fEmail_'); $ciphertext_file = tempnam('', '__fEmail_'); $headers_array = array('To' => $to, 'Subject' => $subject); preg_match_all('#^([\\w\\-]+):\\s+([^\\n]+\\n( [^\\n]+\\n)*)#im', $headers, $header_matches, PREG_SET_ORDER); foreach ($header_matches as $header_match) { $headers_array[$header_match[1]] = trim($header_match[2]); } $body_headers = ""; if (isset($headers_array['Content-Type'])) { $body_headers .= 'Content-Type: ' . $headers_array['Content-Type'] . "\r\n"; } if (isset($headers_array['Content-Transfer-Encoding'])) { $body_headers .= 'Content-Transfer-Encoding: ' . $headers_array['Content-Transfer-Encoding'] . "\r\n"; } if ($body_headers) { $body = $body_headers . "\r\n" . $body; } file_put_contents($plaintext_file, $body); file_put_contents($ciphertext_file, ''); // Set up the neccessary S/MIME resources if ($this->smime_sign) { $senders_smime_cert = file_get_contents($this->senders_smime_cert_file); $senders_private_key = openssl_pkey_get_private(file_get_contents($this->senders_smime_pk_file), $this->senders_smime_pk_password); if ($senders_private_key === FALSE) { throw new fValidationException("The sender's S/MIME private key password specified does not appear to be valid for the private key"); } } if ($this->smime_encrypt) { $recipients_smime_cert = file_get_contents($this->recipients_smime_cert_file); } // If we are going to sign and encrypt, the best way is to sign, encrypt and then sign again if ($this->smime_encrypt && $this->smime_sign) { openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, array()); openssl_pkcs7_encrypt($ciphertext_file, $plaintext_file, $recipients_smime_cert, array(), NULL, OPENSSL_CIPHER_RC2_128); openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, $headers_array); } elseif ($this->smime_sign) { openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, $headers_array); } elseif ($this->smime_encrypt) { openssl_pkcs7_encrypt($plaintext_file, $ciphertext_file, $recipients_smime_cert, $headers_array, NULL, OPENSSL_CIPHER_RC2_128); } // It seems that the contents of the ciphertext is not always \r\n line breaks $message = file_get_contents($ciphertext_file); $message = str_replace("\r\n", "\n", $message); $message = str_replace("\r", "\n", $message); $message = str_replace("\n", "\r\n", $message); list($new_headers, $new_body) = explode("\r\n\r\n", $message, 2); $new_headers = preg_replace('#^To:[^\\n]+\\n( [^\\n]+\\n)*#mi', '', $new_headers); $new_headers = preg_replace('#^Subject:[^\\n]+\\n( [^\\n]+\\n)*#mi', '', $new_headers); $new_headers = preg_replace("#^MIME-Version: 1.0\r?\n#mi", '', $new_headers, 1); $new_headers = preg_replace('#^Content-Type:\\s+' . preg_quote($headers_array['Content-Type'], '#') . "\r?\n#mi", '', $new_headers); $new_headers = preg_replace('#^Content-Transfer-Encoding:\\s+' . preg_quote($headers_array['Content-Transfer-Encoding'], '#') . "\r?\n#mi", '', $new_headers); unlink($plaintext_file); unlink($ciphertext_file); if ($this->smime_sign) { openssl_pkey_free($senders_private_key); } return array($new_headers, $new_body); }
function smime_encrypt($message, $target_cert = NULL) { if (!$target_cert) { /* Cannot encrypt without a target certificate. */ return $message; } $msg_file = writeDataToTempFile($message, "msg-"); $out_file = tempnam(sys_get_temp_dir(), "smime-"); /* No mail headers */ $headers = array(); if (openssl_pkcs7_encrypt($msg_file, $out_file, $target_cert, $headers)) { /* SUCCESS */ smime_debug("smime_sign_message succeeded."); $message = file_get_contents($out_file); } else { /* FAILURE */ error_log("smime_encrypt failed."); } unlink($msg_file); unlink($out_file); return $message; }
/** * Creates a new encrypted button HTML block * * @param array $buttonParams The button parameters as key/value pairs * @return mixed A string of HTML or a Paypal error object on failure */ private function encryptButton($buttonParams) { $merchant_cert = $this->paypalConfig["vendor_cert"]; $merchant_key = $this->paypalConfig["vendor_key"]; $end_cert = $this->paypalConfig["enc_cert"]; $tmpin_file = tempnam('/tmp', 'paypal_'); $tmpout_file = tempnam('/tmp', 'paypal_'); $tmpfinal_file = tempnam('/tmp', 'paypal_'); $rawdata = array(); $buttonParams['cert_id'] = $this->paypalConfig["cert_id"]; foreach ($buttonParams as $name => $value) { $rawdata[] = "{$name}={$value}"; } $rawdata = implode("\n", $rawdata); $fp = fopen($tmpin_file, 'w'); if (!$fp) { echo "Could not open temporary file '{$tmpin_file}')"; return false; # return PayPal::raiseError("Could not open temporary file '$tmpin_file')"); } fwrite($fp, $rawdata); fclose($fp); if (!@openssl_pkcs7_sign($tmpin_file, $tmpout_file, $merchant_cert, array($merchant_key, $this->paypalConfig["private_key_password"]), array(), PKCS7_BINARY)) { echo "Could not sign encrypted data: " . openssl_error_string(); return false; # return PayPal::raiseError("Could not sign encrypted data: " . openssl_error_string()); } $data = file_get_contents($tmpout_file); $data = explode("\n\n", $data); $data = $data[1]; $data = base64_decode($data); $fp = fopen($tmpout_file, 'w'); if (!$fp) { echo "Could not open temporary file '{$tmpin_file}')"; return false; # return PayPal::raiseError("Could not open temporary file '$tmpin_file')"); } fwrite($fp, $data); fclose($fp); if (!@openssl_pkcs7_encrypt($tmpout_file, $tmpfinal_file, $end_cert, array(), PKCS7_BINARY)) { echo "Could not encrypt data:" . openssl_error_string(); return false; # return PayPal::raiseError("Could not encrypt data:" . openssl_error_string()); } $encdata = @file_get_contents($tmpfinal_file, false); if (!$encdata) { echo "Encryption and signature of data failed."; return false; # return PayPal::raiseError("Encryption and signature of data failed."); } $encdata = explode("\n\n", $encdata); $encdata = trim(str_replace("\n", '', $encdata[1])); $encdata = "-----BEGIN PKCS7-----{$encdata}-----END PKCS7-----"; @unlink($tmpfinal_file); @unlink($tmpin_file); @unlink($tmpout_file); return $encdata; }
function process_button() { global $customer_id, $order, $sendto, $currency, $cart_PayPal_Standard_ID, $shipping; $process_button_string = ''; $parameters = array('cmd' => '_xclick', 'item_name' => STORE_NAME, 'shipping' => $this->format_raw($order->info['shipping_cost']), 'tax' => $this->format_raw($order->info['tax']), 'business' => MODULE_PAYMENT_PAYPAL_STANDARD_ID, 'amount' => $this->format_raw($order->info['total'] - $order->info['shipping_cost'] - $order->info['tax']), 'currency_code' => $currency, 'invoice' => substr($cart_PayPal_Standard_ID, strpos($cart_PayPal_Standard_ID, '-') + 1), 'custom' => $customer_id, 'no_note' => '1', 'notify_url' => tep_href_link('ext/modules/payment/paypal/standard_ipn.php', '', 'SSL', false, false), 'return' => tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'), 'cancel_return' => tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'), 'bn' => 'osCommerce22_Default_ST', 'paymentaction' => MODULE_PAYMENT_PAYPAL_STANDARD_TRANSACTION_METHOD == 'Sale' ? 'sale' : 'authorization'); if (is_numeric($sendto) && $sendto > 0) { $parameters['address_override'] = '1'; $parameters['first_name'] = $order->delivery['firstname']; $parameters['last_name'] = $order->delivery['lastname']; $parameters['address1'] = $order->delivery['street_address']; $parameters['city'] = $order->delivery['city']; $parameters['state'] = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], $order->delivery['state']); $parameters['zip'] = $order->delivery['postcode']; $parameters['country'] = $order->delivery['country']['iso_code_2']; } else { $parameters['no_shipping'] = '1'; $parameters['first_name'] = $order->billing['firstname']; $parameters['last_name'] = $order->billing['lastname']; $parameters['address1'] = $order->billing['street_address']; $parameters['city'] = $order->billing['city']; $parameters['state'] = tep_get_zone_code($order->billing['country']['id'], $order->billing['zone_id'], $order->billing['state']); $parameters['zip'] = $order->billing['postcode']; $parameters['country'] = $order->billing['country']['iso_code_2']; } if (tep_not_null(MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE)) { $parameters['page_style'] = MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE; } if (MODULE_PAYMENT_PAYPAL_STANDARD_EWP_STATUS == 'True') { $parameters['cert_id'] = MODULE_PAYMENT_PAYPAL_STANDARD_EWP_CERT_ID; $random_string = rand(100000, 999999) . '-' . $customer_id . '-'; $data = ''; reset($parameters); while (list($key, $value) = each($parameters)) { $data .= $key . '=' . $value . "\n"; } $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', 'w'); fwrite($fp, $data); fclose($fp); unset($data); if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) { openssl_pkcs7_sign(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); // remove headers from the signature $signed = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $signed = explode("\n\n", $signed); $signed = base64_decode($signed[1]); $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', 'w'); fwrite($fp, $signed); fclose($fp); unset($signed); openssl_pkcs7_encrypt(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); // remove headers from the encrypted result $data = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); $data = explode("\n\n", $data); $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----'; unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } else { exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -sign -in ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY . ' < ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $fh = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', 'rb'); $data = fread($fh, filesize(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt')); fclose($fh); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } $process_button_string = tep_draw_hidden_field('cmd', '_s-xclick') . tep_draw_hidden_field('encrypted', $data); unset($data); } else { reset($parameters); while (list($key, $value) = each($parameters)) { $process_button_string .= tep_draw_hidden_field($key, $value); } } return $process_button_string; }
/** * @param Swift_FileStream $outputStream * @param Swift_InputByteStream $is * * @throws Swift_IoException */ protected function messageStreamToEncryptedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $is) { $encryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); if (!openssl_pkcs7_encrypt($outputStream->getPath(), $encryptedMessageStream->getPath(), $this->encryptCert, array(), 0, $this->encryptCipher)) { throw new Swift_IoException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string())); } $this->copyFromOpenSSLOutput($encryptedMessageStream, $is); }
function process_button() { global $customer_id, $order, $sendto, $currency, $cart_PayPal_Standard_ID, $shipping, $order_total_modules; $total_tax = $order->info['tax']; // remove shipping tax in total tax value if (isset($shipping['cost'])) { $total_tax -= $order->info['shipping_cost'] - $shipping['cost']; } $process_button_string = ''; $parameters = array('cmd' => '_cart', 'upload' => '1', 'item_name_1' => STORE_NAME, 'shipping_1' => $this->format_raw($order->info['shipping_cost']), 'business' => MODULE_PAYMENT_PAYPAL_STANDARD_ID, 'amount_1' => $this->format_raw($order->info['total'] - $order->info['shipping_cost'] - $total_tax), 'currency_code' => $currency, 'invoice' => substr($cart_PayPal_Standard_ID, strpos($cart_PayPal_Standard_ID, '-') + 1), 'custom' => $customer_id, 'no_note' => '1', 'notify_url' => tep_href_link('ext/modules/payment/paypal/standard_ipn.php', '', 'SSL', false, false), 'rm' => '2', 'return' => tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'), 'cancel_return' => tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'), 'bn' => 'OSCOM23_PS', 'paymentaction' => MODULE_PAYMENT_PAYPAL_STANDARD_TRANSACTION_METHOD == 'Sale' ? 'sale' : 'authorization'); if (defined('MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON') && tep_not_null(MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON) && strlen(MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON) <= 60) { $parameters['cbt'] = MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON; } if (is_numeric($sendto) && $sendto > 0) { $parameters['address_override'] = '1'; $parameters['first_name'] = $order->delivery['firstname']; $parameters['last_name'] = $order->delivery['lastname']; $parameters['address1'] = $order->delivery['street_address']; $parameters['city'] = $order->delivery['city']; $parameters['state'] = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], $order->delivery['state']); $parameters['zip'] = $order->delivery['postcode']; $parameters['country'] = $order->delivery['country']['iso_code_2']; } else { $parameters['no_shipping'] = '1'; $parameters['first_name'] = $order->billing['firstname']; $parameters['last_name'] = $order->billing['lastname']; $parameters['address1'] = $order->billing['street_address']; $parameters['city'] = $order->billing['city']; $parameters['state'] = tep_get_zone_code($order->billing['country']['id'], $order->billing['zone_id'], $order->billing['state']); $parameters['zip'] = $order->billing['postcode']; $parameters['country'] = $order->billing['country']['iso_code_2']; } if (tep_not_null(MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE)) { $parameters['page_style'] = MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE; } $item_params = array(); $line_item_no = 1; foreach ($order->products as $product) { if (DISPLAY_PRICE_WITH_TAX == 'true') { $product_price = $this->format_raw($product['final_price'] + tep_calculate_tax($product['final_price'], $product['tax'])); } else { $product_price = $this->format_raw($product['final_price']); } $item_params['item_name_' . $line_item_no] = $product['name']; $item_params['amount_' . $line_item_no] = $product_price; $item_params['quantity_' . $line_item_no] = $product['qty']; $line_item_no++; } $items_total = $this->format_raw($order->info['subtotal']); $has_negative_price = false; // order totals are processed on checkout confirmation but not captured into a variable if (is_array($order_total_modules->modules)) { foreach ($order_total_modules->modules as $value) { $class = substr($value, 0, strrpos($value, '.')); if ($GLOBALS[$class]->enabled) { for ($i = 0, $n = sizeof($GLOBALS[$class]->output); $i < $n; $i++) { if (tep_not_null($GLOBALS[$class]->output[$i]['title']) && tep_not_null($GLOBALS[$class]->output[$i]['text'])) { if (!in_array($GLOBALS[$class]->code, array('ot_subtotal', 'ot_shipping', 'ot_tax', 'ot_total'))) { $item_params['item_name_' . $line_item_no] = $GLOBALS[$class]->output[$i]['title']; $item_params['amount_' . $line_item_no] = $this->format_raw($GLOBALS[$class]->output[$i]['value']); $items_total += $item_params['amount_' . $line_item_no]; if ($item_params['amount_' . $line_item_no] < 0) { $has_negative_price = true; } $line_item_no++; } } } } } } $paypal_item_total = $items_total + $parameters['shipping_1']; if (DISPLAY_PRICE_WITH_TAX == 'false') { $item_params['tax_cart'] = $this->format_raw($total_tax); $paypal_item_total += $item_params['tax_cart']; } if ($has_negative_price == false && $this->format_raw($paypal_item_total) == $this->format_raw($order->info['total'])) { $parameters = array_merge($parameters, $item_params); } else { $parameters['tax_cart'] = $this->format_raw($total_tax); } if (MODULE_PAYMENT_PAYPAL_STANDARD_EWP_STATUS == 'True') { $parameters['cert_id'] = MODULE_PAYMENT_PAYPAL_STANDARD_EWP_CERT_ID; $random_string = rand(100000, 999999) . '-' . $customer_id . '-'; $data = ''; foreach ($parameters as $key => $value) { $data .= $key . '=' . $value . "\n"; } $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', 'w'); fwrite($fp, $data); fclose($fp); unset($data); if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) { openssl_pkcs7_sign(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); // remove headers from the signature $signed = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $signed = explode("\n\n", $signed); $signed = base64_decode($signed[1]); $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', 'w'); fwrite($fp, $signed); fclose($fp); unset($signed); openssl_pkcs7_encrypt(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); // remove headers from the encrypted result $data = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); $data = explode("\n\n", $data); $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----'; unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } else { exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -sign -in ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt'); exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY . ' < ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt'); $fh = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', 'rb'); $data = fread($fh, filesize(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt')); fclose($fh); unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'); } $process_button_string = tep_draw_hidden_field('cmd', '_s-xclick') . tep_draw_hidden_field('encrypted', $data); unset($data); } else { foreach ($parameters as $key => $value) { $process_button_string .= tep_draw_hidden_field($key, $value); } } return $process_button_string; }
/** * Create encrypted buttons. * * Requires that the plugin is configured to do so, and that the key files * are set up correctly. If an error is encountered, an empty string * is returned so the caller can proceed with an un-encrypted button. * * @since version 0.4.0 * @param array $fields Array of data to encrypt into buttons * @return string Encrypted_value, or empty string on error */ private function _encButton($fields) { global $_CONF, $_PP_CONF; // Make sure button encryption is enabled and needed values are set if ($this->config['encrypt'] != 1 || empty($this->config['prv_key']) || empty($this->config['pub_key']) || empty($this->config['pp_cert']) || $this->cert_id == '') { return ''; } // Now check that the files exist and can be read foreach (array('prv_key', 'pub_key', 'pp_cert') as $idx => $name) { if (!is_file($this->config[$name]) || !is_readable($this->config[$name])) { return ''; } } // Create a temporary file to begin storing our data. If this fails, // then return. $dataFile = tempnam($_PP_CONF['tmpdir'], 'data'); if (!is_writable($dataFile)) { return ''; } $plainText = ''; $signedText = array(); $encText = ''; $pub_key = @openssl_x509_read(file_get_contents($this->config['pub_key'])); if (!$pub_key) { COM_errorLog("Failed reading public key from {$this->config['pub_key']}", 1); return ''; } $prv_key = @openssl_get_privatekey(file_get_contents($this->config['prv_key'])); if (!$prv_key) { COM_errorLog("Failed reading private key from {$this->config['prv_key']}", 1); return ''; } $pp_cert = @openssl_x509_read(file_get_contents($this->config['pp_cert'])); if (!$pp_cert) { COM_errorLog("Failed reading PayPal certificate from {$this->config['pp_cert']}", 1); return ''; } // Make sure this key and certificate belong together if (!openssl_x509_check_private_key($pub_key, $prv_key)) { COM_errorLog("Mismatched private & public keys", 1); return ''; } // Start off the form data with the PayPal certificate ID $plainText .= "cert_id=" . $this->cert_id; // Create the form data by separating each value set by a new line // Make sure that required fields are available. We assume that the // item_number, item_name and amount are in. if (!isset($fields['business'])) { $fields['business'] = $this->receiver_email; } if (!isset($fields['currency_code'])) { $fields['currency_code'] = $this->currency_code; } foreach ($fields as $key => $value) { $plainText .= "\n{$key}={$value}"; } // First create a file for storing the plain text values $fh = fopen($dataFile . '_plain.txt', 'wb'); if ($fh) { fwrite($fh, $plainText); } else { return ''; } @fclose($fh); // Now sign the plaintext values into the signed file //$fh = fopen($dataFile . "_signed.txt", "w+"); if (!openssl_pkcs7_sign($dataFile . '_plain.txt', $dataFile . '_signed.txt', $pub_key, $prv_key, array(), PKCS7_BINARY)) { return ''; } // Parse the signed file between the header and content $signedText = explode("\n\n", file_get_contents($dataFile . '_signed.txt')); // Save only the content but base64 decode it first $fh = fopen($dataFile . '_signed.txt', 'wb'); if ($fh) { fwrite($fh, base64_decode($signedText[1])); } else { return ''; } @fclose($fh); // Now encrypt the signed file we just wrote if (!openssl_pkcs7_encrypt($dataFile . '_signed.txt', $dataFile . '_enc.txt', $pp_cert, array(), PKCS7_BINARY)) { return ''; } // Parse the encrypted file between header and content $encryptedData = explode("\n\n", file_get_contents($dataFile . "_enc.txt")); $encText = $encryptedData[1]; // Delete all of our temporary files @unlink($dataFile); @unlink($dataFile . "_plain.txt"); @unlink($dataFile . "_signed.txt"); @unlink($dataFile . "_enc.txt"); // Return the now-encrypted form content return "-----BEGIN PKCS7-----\n" . $encText . "\n-----END PKCS7-----"; }
/** * Encrypt Account Password * * @param string $desktopPassword * @return string */ public function encryptAccountPassword($x509File, $desktopPassword) { $directory = sys_get_temp_dir(); $filePrefix = "azure"; $pkcs7In = $directory . "/" . $filePrefix . "_in.pkcs7"; $pkcs7Out = $directory . "/" . $filePrefix . "_out.pkcs7"; $certificate = openssl_x509_read(file_get_contents($x509File)); file_put_contents($pkcs7In, $desktopPassword); $ret = openssl_pkcs7_encrypt($pkcs7In, $pkcs7Out, $certificate, array()); if (!$ret) { throw new \RuntimeException("Encrypting Password failed."); } $parts = explode("\n\n", file_get_contents($pkcs7Out)); $body = str_replace("\n", "", $parts[1]); unlink($pkcs7In); unlink($pkcs7Out); return $body; }
function process_button() { global $osC_Customer, $osC_Currencies, $osC_ShoppingCart; if (MODULE_PAYMENT_PAYPAL_IPN_CURRENCY == 'Selected Currency') { $currency = $osC_Currencies->getCode(); } else { $currency = MODULE_PAYMENT_PAYPAL_IPN_CURRENCY; } if (in_array($currency, array('CAD', 'EUR', 'GBP', 'JPY', 'USD')) === false) { $currency = DEFAULT_CURRENCY; } $params = array('cmd' => '_ext-enter', 'redirect_cmd' => '_xclick', 'business' => MODULE_PAYMENT_PAYPAL_IPN_ID, 'item_name' => STORE_NAME, 'amount' => $osC_Currencies->formatRaw($osC_ShoppingCart->getTotal() - $osC_ShoppingCart->getShippingMethod('cost'), $currency), 'first_name' => $osC_ShoppingCart->getBillingAddress('firstname'), 'last_name' => $osC_ShoppingCart->getBillingAddress('lastname'), 'address1' => $osC_ShoppingCart->getBillingAddress('street_address'), 'address2' => $osC_ShoppingCart->getBillingAddress('suburb'), 'city' => $osC_ShoppingCart->getBillingAddress('city'), 'zip' => $osC_ShoppingCart->getBillingAddress('postcode'), 'country' => $osC_ShoppingCart->getBillingAddress('country_iso_code_2'), 'address_override' => '1', 'notify_url' => osc_href_link(FILENAME_CHECKOUT, 'callback&module=' . $this->_code . (!osc_empty(MODULE_PAYMENT_PAYPAL_IPN_SECRET_KEY) ? '&secret=' . MODULE_PAYMENT_PAYPAL_IPN_SECRET_KEY : ''), 'SSL', false, false, true), 'email' => $osC_Customer->getEmailAddress(), 'invoice' => $this->_order_id, 'shipping' => $osC_Currencies->formatRaw($osC_ShoppingCart->getShippingMethod('cost'), $currency), 'currency_code' => $currency, 'lc' => 'EN', 'return' => osc_href_link(FILENAME_CHECKOUT, 'process', 'SSL', null, null, true), 'rm' => '2', 'no_note' => '1', 'cancel_return' => osc_href_link(FILENAME_CHECKOUT, 'payment', 'SSL', null, null, true), 'paymentaction' => 'authorization'); if ($osC_ShoppingCart->getBillingAddress('country_iso_code_2') == 'US') { $params['state'] = $osC_ShoppingCart->getBillingAddress('zone_code'); } if (MODULE_PAYMENT_PAYPAL_IPN_EWP_STATUS == '1') { $params['cert_id'] = MODULE_PAYMENT_PAYPAL_IPN_EWP_CERT_ID; $random_string = $osC_Customer->getID() . '-' . time() . '-' . osc_create_random_string(5) . '-'; $data = ''; foreach ($params as $key => $value) { $data .= $key . '=' . $value . "\n"; } $fp = fopen(DIR_FS_WORK . $random_string . 'data.txt', 'w'); fwrite($fp, $data); fclose($fp); unset($data); unset($fp); if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) { openssl_pkcs7_sign(DIR_FS_WORK . $random_string . 'data.txt', DIR_FS_WORK . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_IPN_ID), PKCS7_BINARY); unlink(DIR_FS_WORK . $random_string . 'data.txt'); // remove headers from the signature $signed = file_get_contents(DIR_FS_WORK . $random_string . 'signed.txt'); $signed = explode("\n\n", $signed); $signed = base64_decode($signed[1]); $fp = fopen(DIR_FS_WORK . $random_string . 'signed.txt', 'w'); fwrite($fp, $signed); fclose($fp); unset($signed); unset($fp); openssl_pkcs7_encrypt(DIR_FS_WORK . $random_string . 'signed.txt', DIR_FS_WORK . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_IPN_ID), PKCS7_BINARY); unlink(DIR_FS_WORK . $random_string . 'signed.txt'); // remove headers from the encrypted result $data = file_get_contents(DIR_FS_WORK . $random_string . 'encrypted.txt'); $data = explode("\n\n", $data); $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----'; unlink(DIR_FS_WORK . $random_string . 'encrypted.txt'); } else { exec(MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL . ' smime -sign -in ' . DIR_FS_WORK . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . DIR_FS_WORK . $random_string . 'signed.txt'); unlink(DIR_FS_WORK . $random_string . 'data.txt'); exec(MODULE_PAYMENT_PAYPAL_IPN_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_IPN_EWP_PAYPAL_KEY . ' < ' . DIR_FS_WORK . $random_string . 'signed.txt > ' . DIR_FS_WORK . $random_string . 'encrypted.txt'); unlink(DIR_FS_WORK . $random_string . 'signed.txt'); $fp = fopen(DIR_FS_WORK . $random_string . 'encrypted.txt', 'rb'); $data = fread($fp, filesize(DIR_FS_WORK . $random_string . 'encrypted.txt')); fclose($fp); unset($fp); unlink(DIR_FS_WORK . $random_string . 'encrypted.txt'); } $process_button_string = osc_draw_hidden_field('cmd', '_s-xclick') . osc_draw_hidden_field('encrypted', $data); unset($data); } else { $process_button_string = ''; foreach ($params as $key => $value) { $process_button_string .= osc_draw_hidden_field($key, $value); } } return $process_button_string; }
/** * Using the previously set certificates and tempFileDirectory encrypt the button information. * * @param array $parameters Array with parameter names as keys. * @return string The encrypted string for the _s_xclick button form field. * @access public */ public function encryptButton($parameters) { // Check encryption data is available. if ($this->certificateID == '' || !isset($this->certificate) || !isset($this->paypalCertificate)) { return false; } $clearText = ''; $encryptedText = ''; // initialize data. $data = "cert_id=" . $this->certificateID . "\n"; foreach ($parameters as $k => $v) { $d[] = "{$k}={$v}"; } $data .= join("\n", $d); $dataFile = tempnam($this->tempFileDirectory, 'data'); $out = fopen("{$dataFile}_data.txt", 'wb'); fwrite($out, $data); fclose($out); $out = fopen("{$dataFile}_signed.txt", "w+"); if (!openssl_pkcs7_sign("{$dataFile}_data.txt", "{$dataFile}_signed.txt", $this->certificate, $this->privateKey, array(), PKCS7_BINARY)) { return false; } fclose($out); $signedData = explode("\n\n", file_get_contents("{$dataFile}_signed.txt")); $out = fopen("{$dataFile}_signed.txt", 'wb'); fwrite($out, base64_decode($signedData[1])); fclose($out); if (!openssl_pkcs7_encrypt("{$dataFile}_signed.txt", "{$dataFile}_encrypted.txt", $this->paypalCertificate, array(), PKCS7_BINARY)) { return false; } $encryptedData = explode("\n\n", file_get_contents("{$dataFile}_encrypted.txt")); $encryptedText = $encryptedData[1]; @unlink($dataFile); @unlink("{$dataFile}_data.txt"); @unlink("{$dataFile}_signed.txt"); @unlink("{$dataFile}_encrypted.txt"); return $encryptedText; }
/** * Compute encryption key * @param String $user_pass user password * @param String $owner_pass user password * @param String $protection protection type * @access protected * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ protected function _generateencryptionkey($user_pass, $owner_pass, $protection) { $keybytelen = $this->encryptdata['Length'] / 8; if (!$this->encryptdata['pubkey']) { // standard mode // Pad passwords $user_pass = substr($user_pass . $this->enc_padding, 0, 32); $owner_pass = substr($owner_pass . $this->enc_padding, 0, 32); // Compute O value $this->encryptdata['O'] = $this->_Ovalue($user_pass, $owner_pass); // get default permissions (reverse byte order) $permissions = $this->getEncPermissionsString($protection); // Compute encryption key $tmp = $this->_md5_16($user_pass . $this->encryptdata['O'] . $permissions . $this->encryptdata['fileid']); if ($this->encryptdata['mode'] > 0) { for ($i = 0; $i < 50; ++$i) { $tmp = $this->_md5_16(substr($tmp, 0, $keybytelen)); } } $this->encryptdata['key'] = substr($tmp, 0, $keybytelen); // Compute U value $this->encryptdata['U'] = $this->_Uvalue(); // Compute P value $this->encryptdata['P'] = $protection; } else { // Public-Key mode // random 20-byte seed $seed = sha1(microtime() . uniqid('' . rand()) . $this->file_id, true); $recipient_bytes = ''; foreach ($this->encryptdata['pubkeys'] as $pubkey) { // for each public certificate if (isset($pubkey['p'])) { $pkprotection = $this->getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']); } else { $pkprotection = $protection; } // get default permissions (reverse byte order) $pkpermissions = $this->getEncPermissionsString($pkprotection); // envelope data $envelope = $seed . $pkpermissions; // write the envelope data to a temporary file $tempkeyfile = tempnam(K_PATH_CACHE, 'tmpkey_'); $f = fopen($tempkeyfile, 'wb'); if (!$f) { $this->Error('Unable to create temporary key file: ' . $tempkeyfile); } $envelope_lenght = strlen($envelope); fwrite($f, $envelope, $envelope_lenght); fclose($f); $tempencfile = tempnam(K_PATH_CACHE, 'tmpenc_'); if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_DETACHED | PKCS7_BINARY)) { $this->Error('Unable to encrypt the file: ' . $tempkeyfile); } unlink($tempkeyfile); // read encryption signature $signature = file_get_contents($tempencfile, false, null, $envelope_lenght); unlink($tempencfile); // extract signature $signature = substr($signature, strpos($signature, 'Content-Disposition')); $tmparr = explode("\n\n", $signature); $signature = trim($tmparr[1]); unset($tmparr); // decode signature $signature = base64_decode($signature); // convert signature to hex $hexsignature = current(unpack('H*', $signature)); // store signature on recipients array $this->encryptdata['Recipients'][] = $hexsignature; // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array $recipient_bytes .= $signature; } // calculate encryption key $this->encryptdata['key'] = substr(sha1($seed . $recipient_bytes, true), 0, $keybytelen); } }