public function seal($data) { $key = $this->_getKeyResource(); if (openssl_seal($data, $sealed, $ekeys, array($key)) === false) { throw new Relax_Openssl_Exception("Error sealing: " . openssl_error_string()); } return array($sealed, $ekeys[0]); }
/** * * @param string $data * @param string $publicKey * @return string */ public function encryptData($data, $publicKey) { $cryptedData = null; $envelopeKeys = null; openssl_seal($data, $cryptedData, $envelopeKeys, array($publicKey)); $envelopeKey = $envelopeKeys[0]; $crypted = base64_encode($envelopeKey) . ':' . base64_encode($cryptedData); return $crypted; }
public static function seal($myData, $publicKey) { openssl_seal($myData, $sealed, $ekeys, array($publicKey)); $sealed = base64_encode($sealed); $Xevk = base64_encode($ekeys[0]); return $sealed . '@' . $Xevk; }
public function encryptMessage($message) { $cipher = $e = null; // These are passed by reference, so they are changed after the seal openssl_seal($message, $cipher, $e, [$this->publicKey]); $this->sealedData = base64_encode($cipher); $this->envelope = base64_encode($e[0]); // These must either be stored in a database or in a file somewhere. }
public function seal($data, array $pubKeys) { $sealed = null; $ekeys = []; openssl_seal($data, $sealed, $ekeys, $pubKeys); array_walk($ekeys, function (&$key) { $key = $this->encode($key); }); return ['sealed' => $this->encode($sealed), 'keys' => $ekeys]; }
/** * Encrypts data with the supplied public key object and returns an EncryptedData object containing * the encrypted data with the key. * * @param string $data * @param Pub $key * @return EncryptedData */ public function encrypt($data, Pub $key) { $encData = ''; $encKeys = array(); if (!openssl_seal($data, $encData, $encKeys, array($key->asResource()))) { throw new \Exception(sprintf("Error encrypting data with public key: %s", openssl_error_string())); } $encKey = $encKeys[0]; require_once 'OpenSslCrypt/EncryptedData.php'; return new EncryptedData($encKey, $encData); }
/** * Encrypt data with the <em>public</em> key of the recipient. * Will be encrypted using openssl_seal. * * @param $data string The data to encrypt * @param $key string The public key for encryption (as PEM formatted string) * @return string The encrypted data */ public function encrypt($data, $publicKey) { $publicKey = $this->decodeKey($publicKey); if (empty($publicKey)) { throw new \Exception('Public key missing', 1423738632); } openssl_seal($data, $cryptedData, $envelopeKeys, array($publicKey)); $envelopeKey = $envelopeKeys[0]; $crypted = base64_encode($envelopeKey) . ':' . base64_encode($cryptedData); return $crypted; }
/** * encrypt text usgin RSA RC4 algorithm * @param string $plaintext some plain text * @return RSA encrypted text * */ function cifrar_RSA_RC4($plaintext) { $publicKey = openssl_pkey_get_public('file://' . $_SESSION['APP_PATH'] . 'backend/public.key'); // obtiene la clave publica $encrypted = ''; $a_envelope = array(); // array para almacenar clave de descifrado $a_key = array($publicKey); // obtiene la clave if (openssl_seal($plaintext, $encrypted, $a_envelope, $a_key) === FALSE) die('Failed to encrypt data'); // trata de descifrar openssl_free_key($publicKey); // devuelve un array con el dato cifrado y una clave de descifrado en base64 $data = array('data' => base64_encode($encrypted), 'envelope' => base64_encode($a_envelope[0])); return $data; }
/** * Get environment and request data as encrypted base64 string. * * @param array * @param string * @return string */ public static function encrypt($data, $public) { self::checkAvailability(); $message = sprintf("Exception [%s]: %s\n URL: %s\n\n%s", $data['exception'], $data['message'], $data['request'], $data['trace']); $public = openssl_pkey_get_public($public); if (!$public) { throw new \RuntimeException('Public key can not be loaded.'); } $encrypted = ''; $envelopes = []; if (!openssl_seal($message, $encrypted, $envelopes, [$public])) { throw new \RuntimeException('Data can not be encrypted.'); } return base64_encode(serialize([$envelopes[0], $encrypted])); }
/** * Encode data in json and send with APP CYD pubkey * @param type $data : data array * @return string : encoded string */ public static function encodeData($data) { $retour = false; // Get APP public key $dir = dirname(__FILE__); $pubkey = openssl_pkey_get_public('file://' . $dir . '/ssl/publickey.cer'); // encoding if ($pubkey !== false) { $ekeys = array(); $crypted = ''; if (openssl_seal(Tools::jsonEncode($data), $crypted, $ekeys, array($pubkey))) { $retour = array('key' => urlencode($ekeys[0]), 'data' => urlencode($crypted)); } openssl_free_key($pubkey); } return $retour; }
/** * @param string $plainContent * @param array $keyFiles * @return array * @throws MultiKeyEncryptException */ public function multiKeyEncrypt($plainContent, array $keyFiles) { // openssl_seal returns false without errors if plaincontent is empty // so trigger our own error if (empty($plainContent)) { throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content'); } // Set empty vars to be set by openssl by reference $sealed = ''; $shareKeys = []; $mappedShareKeys = []; if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles)) { $i = 0; // Ensure each shareKey is labelled with its corresponding key id foreach ($keyFiles as $userId => $publicKey) { $mappedShareKeys[$userId] = $shareKeys[$i]; $i++; } return ['keys' => $mappedShareKeys, 'data' => $sealed]; } else { throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string()); } }
/** * Encrypts the passed data using public key encryption via OpenSSL * * A public key (X.509 certificate) is required for encryption and a * private key (PEM) is required for decryption. * * @param string $plaintext The content to be encrypted * @param string $public_key_file The path to an X.509 public key certificate * @return string A base-64 encoded result containing a Flourish fingerprint and suitable for decryption using ::publicKeyDecrypt() */ public static function publicKeyEncrypt($plaintext, $public_key_file) { self::verifyPublicKeyEnvironment(); $public_key_resource = self::createPublicKeyResource($public_key_file); $ciphertext = ''; $encrypted_keys = array(); $result = openssl_seal($plaintext, $ciphertext, $encrypted_keys, array($public_key_resource)); openssl_free_key($public_key_resource); if ($result === FALSE) { throw new fEnvironmentException('There was an unknown error encrypting the plaintext provided'); } $hmac = hash_hmac('sha1', $encrypted_keys[0] . $ciphertext, $plaintext); return 'fCryptography::public#' . base64_encode($encrypted_keys[0]) . '#' . base64_encode($ciphertext) . '#' . $hmac; }
<?php $pubkey = openssl_pkey_get_public(file_get_contents('selfcert.pem')); $privkey = openssl_pkey_get_private(file_get_contents('privkey.pem')); $message = 'hello,world'; $cipher_text = NULL; $plain_text = NULL; $keys = NULL; openssl_seal($message, $cipher_text, $keys, array($pubkey)); $file = fopen('wrapped.bin', 'wb'); fwrite($file, $keys[0]); fclose($file); $file = fopen('data.bin', 'wb'); fwrite($file, $cipher_text); fclose($file);
/** * Seal data using this public key. This method returns two strings, * the first one being the encoded data, the second a key that has to * be passed to the recipient, too. * * @param string data * @return string[] first element is data, second is the key * @throws security.crypto.CryptoException if the operation fails */ public function seal($data) { if (FALSE === openssl_seal($data, $sealed, $keys, array($this->_hdl))) { throw new CryptoException('Could not seal data', OpenSslUtil::getErrors()); } return array($sealed, $keys[0]); }
<?php $data = "openssl_seal() test"; $cipher = 'AES-128-CBC'; $pub_key = "file://" . dirname(__FILE__) . "/public.key"; $priv_key = "file://" . dirname(__FILE__) . "/private.key"; openssl_seal($data, $sealed, $ekeys, array($pub_key, $pub_key), $cipher); openssl_seal($data, $sealed, $ekeys, array($pub_key, $pub_key), 'sparkles', $iv); openssl_seal($data, $sealed, $ekeys, array($pub_key, $pub_key), $cipher, $iv); openssl_open($sealed, $decrypted, $ekeys[0], $priv_key, $cipher, $iv); echo $decrypted;
/** * Encrypt a message and return it in an XML-Encrypted document * * This function can encrypt any content, but it was written to provide a system * of encrypting XML-RPC request and response messages. The message will be * base64 encoded, so it does not need to be text - binary data should work. * * We compute the SHA1 digest of the message. * We compute a signature on that digest with our private key. * We link to the public key that can be used to verify our signature. * We base64 the message data. * We identify our wwwroot - this must match our certificate's CN * * The XML-RPC document will be parceled inside an XML-SIG document, which holds * the base64_encoded XML as an object, the SHA1 digest of that document, and a * signature of that document using the local private key. This signature will * uniquely identify the RPC document as having come from this server. * * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c * site * * @param string $message The data you want to sign * @param string $remote_certificate Peer's certificate in PEM format * @return string An XML-ENC document */ function mnet_encrypt_message($message, $remote_certificate) { global $MNET; // Generate a key resource from the remote_certificate text string $publickey = openssl_get_publickey($remote_certificate); if (gettype($publickey) != 'resource') { // Remote certificate is faulty. return false; } // Initialize vars $encryptedstring = ''; $symmetric_keys = array(); // passed by ref -> &$encryptedstring &$symmetric_keys $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey)); $message = $encryptedstring; $symmetrickey = array_pop($symmetric_keys); $message = '<?xml version="1.0" encoding="iso-8859-1"?> <encryptedMessage> <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/> <ds:KeyName>XMLENC</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>' . base64_encode($message) . '</CipherValue> </CipherData> </EncryptedData> <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:KeyName>SSLKEY</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>' . base64_encode($symmetrickey) . '</CipherValue> </CipherData> <ReferenceList> <DataReference URI="#ED"/> </ReferenceList> <CarriedKeyName>XMLENC</CarriedKeyName> </EncryptedKey> <wwwroot>' . $MNET->wwwroot . '</wwwroot> </encryptedMessage>'; return $message; }
/** * Encrypt a message and return it in an XML-Encrypted document * * This function can encrypt any content, but it was written to provide a system * of encrypting XML-RPC request and response messages. The message does not * need to be text - binary data should work. * * Asymmetric keys can encrypt only small chunks of data. Usually 1023 or 2047 * characters, depending on the key size. So - we generate a symmetric key and * use the asymmetric key to secure it for transport with the data. * * We generate a symmetric key * We encrypt the symmetric key with the public key of the remote host * We encrypt our content with the symmetric key * We base64 the key & message data. * We identify our wwwroot - this must match our certificate's CN * * Normally, the XML-RPC document will be parceled inside an XML-SIG envelope. * We parcel the XML-SIG document inside an XML-ENC envelope. * * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c * site * * @param string $message The data you want to sign * @param string $remote_certificate Peer's certificate in PEM format * @return string An XML-ENC document */ function xmlenc_envelope($message, $remote_certificate) { // Generate a key resource from the remote_certificate text string $publickey = openssl_get_publickey($remote_certificate); if (gettype($publickey) != 'resource') { // Remote certificate is faulty. throw new MaharaException('Could not generate public key resource from certificate', 1); } // Initialize vars $wwwroot = dropslash(get_config('wwwroot')); $encryptedstring = ''; $symmetric_keys = array(); // passed by ref -> &$encryptedstring &$symmetric_keys $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey)); $message = base64_encode($encryptedstring); $symmetrickey = base64_encode(array_pop($symmetric_keys)); $zed = 'nothing'; return <<<EOF <?xml version="1.0" encoding="iso-8859-1"?> <encryptedMessage> <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/> <ds:KeyName>XMLENC</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>{$message}</CipherValue> </CipherData> </EncryptedData> <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:KeyName>SSLKEY</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>{$symmetrickey}</CipherValue> </CipherData> <ReferenceList> <DataReference URI="#ED"/> </ReferenceList> <CarriedKeyName>XMLENC</CarriedKeyName> </EncryptedKey> <wwwroot>{$wwwroot}</wwwroot> <X1>{$zed}</X1> </encryptedMessage> EOF; }
/** * Seals the given message in an encrypted envelope that can only be decrypted by the private key matching the public key. * * @param string $message The message to be sealed. * @param string $cipherMethod The cipher method to use from CipherMethod. * @param string $iv The optional initialization vector for some cipher methods. * @return array Returns an array containing the envelope along other information like the key and method used. * 0 => [string] envelope * 1 => [string] envelope key * 2 => [string] cipher method used * @since 0.3 */ public function seal(string $message, string $cipherMethod = CipherMethod::RC4, string $iv = '') : array { OpenSSL::resetErrors(); if (!CipherMethod::isAvailable($cipherMethod)) { throw new CipherMethodNotAvailableException($cipherMethod, 'The given cipher method is not available in the current platform stack.'); } $paddedIV = InitVector::pad($iv); if (@openssl_seal($message, $envelope, $envelopeKeys, [$this->resource], $cipherMethod, $paddedIV) === false) { // @codeCoverageIgnoreStart throw new OpenSSLException(OpenSSL::getErrors(), 'Could not seal message.'); // @codeCoverageIgnoreEnd } return [$envelope, $envelopeKeys[0], $cipherMethod]; }
/** * Create asymmetrically encrypted keyfile content using a generated key * @param string $plainContent content to be encrypted * @param array $publicKeys array keys must be the userId of corresponding user * @return array keys: keys (array, key = userId), data * @throws \OCA\Files_Encryption\Exception\MultiKeyEncryptException if encryption failed * @note symmetricDecryptFileContent() can decrypt files created using this method */ public static function multiKeyEncrypt($plainContent, array $publicKeys) { // openssl_seal returns false without errors if $plainContent // is empty, so trigger our own error if (empty($plainContent)) { throw new Exception\MultiKeyEncryptException('Cannot multiKeyEncrypt empty plain content', Exception\MultiKeyEncryptException::EMPTY_DATA); } // Set empty vars to be set by openssl by reference $sealed = ''; $shareKeys = array(); $mappedShareKeys = array(); if (openssl_seal($plainContent, $sealed, $shareKeys, $publicKeys)) { $i = 0; // Ensure each shareKey is labelled with its // corresponding userId foreach ($publicKeys as $userId => $publicKey) { $mappedShareKeys[$userId] = $shareKeys[$i]; $i++; } return array('keys' => $mappedShareKeys, 'data' => $sealed); } else { throw new Exception\MultiKeyEncryptException('multi key encryption failed: ' . openssl_error_string(), Exception\MultiKeyEncryptException::OPENSSL_SEAL_FAILED); } }
/** * access Mobilpay.Ro secure payment portal * * @param resource $public_key - obtained by calling openssl_pkey_get_public * @param string &$env_key - returns envelope key base64 encoded or null if function fails * @param string &$enc_data - returns data to post base64 encoded or null if function fails * * @return boolean */ public function buildAccessParameters($public_key, &$env_key, &$enc_data) { $params = $this->builParametersList(); if (is_null($params)) { return false; } $src_data = self::buildQueryString($params); $enc_data = ''; $env_keys = array(); $result = openssl_seal($src_data, $enc_data, $env_keys, array($public_key)); if ($result === false) { $env_key = null; $enc_data = null; return false; } $env_key = base64_encode($env_keys[0]); $enc_data = base64_encode($enc_data); return true; }
<?php // Get the full message text into a variable $fullText = 'My Hovercraft is full of eels'; $encryptedText = ''; // Load the public key into an array $publicKeys[] = openssl_get_publickey(file_get_contents('srvr-pub.key')); // Encrypt the $fullText and return the $encryptedText and the $encryptedKeys $res = openssl_seal($fullText, $encryptedText, $encryptedKeys, $publicKeys); // Setup a couple filenames to store the text and its key $dataFile = 'data.txt'; $keyFile = 'data.key'; // Write the order files file_put_contents($dataFile, base64_encode($encryptedText)); file_put_contents($keyFile, base64_encode($encryptedKeys[0])); /* // ---------Another Method------------ // ------ENCRYPT------ $plaintext = 'My Hovercraft is full of eels'; $publicKey = openssl_pkey_get_public('file://public.key'); $encrypted = ''; $a_envelope = array(); $a_key = array($publicKey); if (openssl_seal($plaintext, $encrypted, $a_envelope, $a_key) === FALSE) die('Failed to encrypt data'); openssl_free_key($publicKey); // ------DECRYPT------ if (!$privateKey = openssl_pkey_get_private('file://private.key')) die('Private Key failed'); $decrypted = ''; if (openssl_open($encrypted, $decrypted, $envelope, $privateKey) === FALSE)
/** * Encrypts the file $value with the defined settings * Note that you also need the "encrypted" keys to be able to decrypt * * @param string $value Content to encrypt * @return string The encrypted content * @throws Zend_Filter_Exception */ public function encrypt($value) { $encrypted = array(); $encryptedkeys = array(); if (count($this->_keys['public']) == 0) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Openssl can not encrypt without public keys'); } foreach ($this->_keys['public'] as $key => $cert) { $keys[$key] = openssl_pkey_get_public($cert); } $crypt = openssl_seal($value, $encrypted, $encryptedkeys, $keys); foreach ($keys as $key) { openssl_free_key($key); } if ($crypt === false) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Openssl was not able to encrypt you content with the given options'); } $this->_keys['envelope'] = $encryptedkeys; return $encrypted; }
function qs_queryQS($action, $data = '', $fast = false) { global $qs_public_key; // generate new private key $key = openssl_pkey_new(); openssl_pkey_export($key, $private_key); $public_key = openssl_pkey_get_details($key); $public_key = $public_key["key"]; $message = qs_base64_serialize(array('key' => $public_key, 'data' => $data)); openssl_seal($message, $message, $server_key, array($qs_public_key)); $message = qs_base64_serialize(array('key' => $server_key[0], 'data' => $message)); $data = "message=" . $message; // connect to qts if ($fast) { $fp = fsockopen('www.qianqin.de', 80, $errno, $errstr, QS_FAST_TIMEOUT); stream_set_timeout($fp, QS_FAST_TIMEOUT); } else { $fp = fsockopen('www.qianqin.de', 80); } if (!$fp) { return false; } fputs($fp, "POST /qtranslate/services/{$action} HTTP/1.1\r\n"); fputs($fp, "Host: www.qianqin.de\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: " . strlen($data) . "\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $data); $res = ''; while (!feof($fp)) { $res .= fgets($fp, 128); } // check for timeout $info = stream_get_meta_data($fp); if ($info['timed_out']) { return false; } fclose($fp); preg_match("#^Content-Length:\\s*([0-9]+)\\s*\$#ism", $res, $match); $content_length = $match[1]; $content = substr($res, -$content_length, $content_length); $debug = $content; $content = qs_base64_unserialize($content); openssl_open($content['data'], $content, $content['key'], $private_key); if ($content === false) { echo "<pre>DEBUG:\n"; echo $debug; echo "</pre>"; } openssl_free_key($key); return qs_cleanup(qs_base64_unserialize($content), $action); }
public function encrypt($x509FilePath) { $this->_prepare(); $publicKey = openssl_pkey_get_public("file://{$x509FilePath}"); if ($publicKey === false) { $this->outEncData = null; $this->outEnvKey = null; $errorMessage = "Error while loading X509 public key certificate! Reason:"; while ($errorString = openssl_error_string()) { $errorMessage .= $errorString . "\n"; } throw new Exception($errorMessage, self::ERROR_LOAD_X509_CERTIFICATE); } $srcData = $this->_xmlDoc->saveXML(); $publicKeys = [$publicKey]; $encData = null; $envKeys = null; $result = openssl_seal($srcData, $encData, $envKeys, $publicKeys); if ($result === false) { $this->outEncData = null; $this->outEnvKey = null; $errorMessage = "Error while encrypting data! Reason:"; while ($errorString = openssl_error_string()) { $errorMessage .= $errorString . "\n"; } throw new Exception($errorMessage, self::ERROR_ENCRYPT_DATA); } $this->outEncData = base64_encode($encData); $this->outEnvKey = base64_encode($envKeys[0]); }
function test_openssl_seal() { $privkey = openssl_pkey_new(); VERIFY($privkey != null); $csr = openssl_csr_new(null, $privkey); VERIFY($csr != null); $pubkey = openssl_csr_get_public_key($csr); VERIFY($pubkey != null); $data = "some secret messages"; VERIFY(openssl_seal($data, $sealed, $ekeys, array($pubkey))); VERIFY(strlen($sealed) > 0); VS(count($ekeys), 1); VERIFY(strlen($ekeys[0]) > 0); VERIFY(openssl_open($sealed, $open_data, $ekeys[0], $privkey)); VS($open_data, $data); VERIFY(openssl_open($sealed, $open_data, $ekeys[0], $privkey, 'RC4')); VS($open_data, $data); VERIFY(openssl_seal($data, $sealed, $ekeys, array($pubkey), 'AES-256-ECB')); VERIFY(strlen($sealed) > 0); VS(count($ekeys), 1); VERIFY(strlen($ekeys[0]) > 0); VERIFY(openssl_open($sealed, $open_data, $ekeys[0], $privkey, 'AES-256-ECB')); VS($open_data, $data); }
public static function seal($data, &$sealedData, &$envKeys, array $pubKeys) { $pubKeyIds = array(); foreach ($pubKeys as $pubKey) { if ($pubKey instanceof PKey) { $pubKeyIds[] = $pubKey->getPublicKey(); } else { throw new OpenSslException('Pub keys must be an array containing PSX\\OpenSsl\\PKey instances'); } } $return = openssl_seal($data, $sealedData, $envKeys, $pubKeyIds); self::handleReturn($return); return $return; }
/** * Encrypt a message. * * @param mixed $data * The data to encrypt. * * @return string * The encrypted text * * @throws SSLEncryptionException */ public function encrypt($data) { $plaintext = json_encode($data); $publicKey = $this->getPublicKey(); $result = openssl_seal($plaintext, $message, $keys, array($publicKey)); if ($result === FALSE || empty($keys[0]) || empty($message) || $message === $plaintext) { throw new SSLEncryptionException('Unable to encrypt a message: ' . openssl_error_string()); } $envelope = (object) array('publicKey' => base64_encode($keys[0]), 'message' => base64_encode($message)); return base64_encode(json_encode($envelope)); }
} // Current date and time $t_date = date("Y-m-d-H:i"); // Sign the message before encrypting. $t_sign = sign_msg($msg); //print base64_encode($sealed); // Sender's public key $user_pub = $_SESSION['s_pub']; // Recepients Public key $recip_pub = $_SESSION['s_recip_pub']; if ($recip_pub == "") { die("Please ensure you have added the user to your list of users to send messages.<br />Check that the user is the dropdown box on your main page."); } /** Encrypt the message with the public key of the sender and receiver. */ /** In the ESCROW implementation of this app, the ESCROW key will be added automatically, as well */ openssl_seal($msg . "::" . $t_sign . "::" . $t_date, $sealed, $ekeys, array($user_pub, $recip_pub)); // Encode the binary data to store in the DB $sealed = base64_encode($sealed); // The $ekeys variable is the random password used to seal the message with RC4 // Those are returned as arrays so each one is base64 encoded. // Retrieve private key and password. $key = $_SESSION['s_priv_tmp']; $pass = $_SESSION['s_pass']; // Encrypt the RC4 key that encrypts the message with the user's public key $seal_keys_0 = e_seal($ekeys[0], $user_pub); $seal_keys_1 = e_seal($ekeys[1], $recip_pub); // Encode the results to store in the database. $seal_keys_0 = base64_encode($seal_keys_0); $seal_keys_1 = base64_encode($seal_keys_1); // concatenate the two to store in the database. $keys_crypt = "@{$seal_keys_0}|{$seal_keys_1}";
/** * Encrypts $value with the defined settings * Note that you also need the "encrypted" keys to be able to decrypt * * @param string $value Content to encrypt * @return string The encrypted content * @throws Zend_Filter_Exception */ public function encrypt($value) { $encrypted = array(); $encryptedkeys = array(); if (count($this->_keys['public']) == 0) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Openssl can not encrypt without public keys'); } $keys = array(); $fingerprints = array(); $count = -1; foreach ($this->_keys['public'] as $key => $cert) { $keys[$key] = openssl_pkey_get_public($cert); if ($this->_package) { $details = openssl_pkey_get_details($keys[$key]); if ($details === false) { $details = array('key' => 'ZendFramework'); } ++$count; $fingerprints[$count] = md5($details['key']); } } // compress prior to encryption if (!empty($this->_compression)) { require_once 'Zend/Filter/Compress.php'; $compress = new Zend_Filter_Compress($this->_compression); $value = $compress->filter($value); } $crypt = openssl_seal($value, $encrypted, $encryptedkeys, $keys); foreach ($keys as $key) { openssl_free_key($key); } if ($crypt === false) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('Openssl was not able to encrypt your content with the given options'); } $this->_keys['envelope'] = $encryptedkeys; // Pack data and envelope keys into single string if ($this->_package) { $header = pack('n', count($this->_keys['envelope'])); foreach ($this->_keys['envelope'] as $key => $envKey) { $header .= pack('H32n', $fingerprints[$key], strlen($envKey)) . $envKey; } $encrypted = $header . $encrypted; } return $encrypted; }
/** * Seal data using this public key. This method returns two strings, * the first one being the encoded data, the second a key that has to * be passed to the recipient, too. * * @param string data * @return string[] first element is data, second is the key * @throws security.crypto.CryptoException if the operation fails */ public function seal($data) { if (false === openssl_seal($data, $sealed, $keys, [$this->_hdl])) { throw new CryptoException('Could not seal data', OpenSslUtil::getErrors()); } return [$sealed, $keys[0]]; }