/** * @param string $data * @param string $nonce * @param string $senderPrivateKey * @param string $recipientPublicKey * @return string encrypted box */ protected function makeBox($data, $nonce, $senderPrivateKey, $recipientPublicKey) { /** @noinspection PhpUndefinedNamespaceInspection @noinspection PhpUndefinedFunctionInspection */ $kp = \Sodium\crypto_box_keypair_from_secretkey_and_publickey($senderPrivateKey, $recipientPublicKey); /** @noinspection PhpUndefinedNamespaceInspection @noinspection PhpUndefinedFunctionInspection */ return \Sodium\crypto_box($data, $nonce, $kp); }
/** * Encrypt a message using public key encryption. * * @param string $message The message to be encrypted. * @param string $sender_private The senders private key. * @param string $receiver_public The receivers public key. * @return string The JSON string for the encrypted message. * @throws InvalidTypeException */ public static function encrypt($message, $sender_private, $receiver_public) { # Test to make sure all the required variables are strings. Helpers::isString($message, 'PublicKeyEncryption', 'encrypt'); Helpers::isString($sender_private, 'PublicKeyEncryption', 'encrypt'); Helpers::isString($receiver_public, 'PublicKeyEncryption', 'encrypt'); # Generate a keypair for the message to be sent. $messageKeyPair = \Sodium\crypto_box_keypair_from_secretkey_and_publickey(Helpers::hex2bin($sender_private), Helpers::hex2bin($receiver_public)); # Generate the nonce for usage. $nonce = Entropy::generateNonce(); # Encrypt the message and return it. return base64_encode(json_encode(['msg' => Helpers::bin2hex(\Sodium\crypto_box($message, $nonce, $messageKeyPair)), 'nonce' => Helpers::bin2hex($nonce)])); }
/** * Encrypt a message with a target users' public key * * @param string $source Message to encrypt * @param string $publicKey * @param boolean $raw Don't hex encode the output? * * @return string */ public static function seal($source, Contract\CryptoKeyInterface $publicKey, $raw = false) { if ($publicKey->isPublicKey()) { if (function_exists('\\Sodium\\crypto_box_seal')) { $sealed = \Sodium\crypto_box_seal($source, $publicKey->get()); } else { /** * Polyfill for libsodium < 1.0.3 */ // Generate an ephemeral keypair $eph_kp = \Sodium\crypto_box_keypair(); $eph_secret = \Sodium\crypto_box_secretkey($eph_kp); $eph_public = \Sodium\crypto_box_publickey($eph_kp); $seal_pubkey = $publicKey->get(); $box_kp = \Sodium\crypto_box_keypair_from_secretkey_and_publickey($eph_secret, $seal_pubkey); // Calculate the nonce $nonce = \Sodium\crypto_generichash($eph_public . $seal_pubkey, null, \Sodium\CRYPTO_BOX_NONCEBYTES); // Seal the message $sealed = $eph_public . \Sodium\crypto_box($source, $nonce, $box_kp); // Don't forget to wipe \Sodium\memzero($seal_pubkey); \Sodium\memzero($eph_kp); \Sodium\memzero($eph_secret); \Sodium\memzero($eph_public); \Sodium\memzero($nonce); \Sodium\memzero($box_kp); } if ($raw) { return $sealed; } return \Sodium\bin2hex($sealed); } throw new CryptoAlert\InvalidKey('Expected a public key'); }
/** * Check if a password is known by the knownpassword.org API. * * @param string $password The password to check. * @param string $passwordFormat The format of the given password (Blake2b, Sha512, Cleartext) [Default: Blake2b]. * @return mixed Exception on error, true if the password is known and false if the password is unknown. * @access public */ public function checkPassword($password, $passwordFormat = "Blake2b") { $apiData = array(); switch ($passwordFormat) { case "Blake2b": $apiData = array("Blake2b" => $password); break; case "Sha512": $apiData = array("Sha512" => $password); break; case "Cleartext": $apiData = array("Cleartext" => $password); break; default: throw new \Exception("Unknown passwordFormat."); } $nonce = \Sodium\randombytes_buf(24); $signature = \Sodium\crypto_sign_detached($nonce, $this->_privatekey); $clearJson = json_encode($apiData); $encryptionNonce = \Sodium\randombytes_buf(\Sodium\CRYPTO_BOX_NONCEBYTES); $encryptionKeyPair = \Sodium\crypto_box_keypair(); $encryptionSecretkey = \Sodium\crypto_box_secretkey($encryptionKeyPair); $encryptionPublickey = \Sodium\crypto_box_publickey($encryptionKeyPair); $encryptionKeyPair = \Sodium\crypto_box_keypair_from_secretkey_and_publickey($encryptionSecretkey, $this->_serverEncryptionPublicKey); $ciphertext = \Sodium\crypto_box($clearJson, $encryptionNonce, $encryptionKeyPair); $encryptedApiData = array("PublicKey" => \Sodium\bin2hex($encryptionPublickey), "Nonce" => \Sodium\bin2hex($encryptionNonce), "Ciphertext" => \Sodium\bin2hex($ciphertext)); $data_string = json_encode($encryptedApiData); $ch = curl_init($this->_apiurl . "/checkpassword"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string), 'User-Agent: ' . 'Laravel 5', 'X-Public: ' . \Sodium\bin2hex($this->_publickey), 'X-Nonce: ' . \Sodium\bin2hex($nonce), 'X-Signature: ' . \Sodium\bin2hex($signature))); if (!($result = curl_exec($ch))) { throw new \Exception("Request failed"); } $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($result, 0, $header_size); $headers = $this->get_headers_from_curl_response($header); if (array_key_exists("http_code", $headers[0]) && array_key_exists("X-Powered-By", $headers[0]) && array_key_exists("X-Signature", $headers[0])) { $httpCode = $headers[0]["http_code"]; $responsePowered = $headers[0]["X-Powered-By"]; $responseSignature = $headers[0]["X-Signature"]; $responseNonce = $headers[0]["X-Nonce"]; if ($httpCode === "HTTP/1.1 200 OK" || $httpCode === "HTTP/2.0 200 OK") { if ($responsePowered === "bitbeans") { // validate the response signature if (!\Sodium\crypto_sign_verify_detached(\Sodium\hex2bin($responseSignature), \Sodium\crypto_generichash(\Sodium\hex2bin($responseNonce), null, 64), $this->_serverSignaturePublicKey)) { throw new \Exception("Invalid signature"); } } else { throw new \Exception("Invalid server"); } } else { throw new \Exception("Invalid response code"); } } else { throw new \Exception("Invalid header"); } $result = substr($result, $header_size); curl_close($ch); $resultJson = json_decode($result); $decryptionKeyPair = \Sodium\crypto_box_keypair_from_secretkey_and_publickey($encryptionSecretkey, \Sodium\hex2bin($resultJson->{'publicKey'})); $plaintext = \Sodium\crypto_box_open(\Sodium\hex2bin($resultJson->{'ciphertext'}), \Sodium\hex2bin($resultJson->{'nonce'}), $decryptionKeyPair); if ($plaintext === FALSE) { throw new \Exception("Malformed message or invalid MAC"); } $plaintextJson = json_decode($plaintext); return !$plaintextJson->{'FoundPassword'}; }