adapter = $adapter; $this->messages = $messages; } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::calculateSharedKey() */ public function calculateSharedKey() { $this->calculateKey(); return $this->secretKey->getX(); } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::createMultiPartyKey() */ public function createMultiPartyKey() { $this->calculateKey(); return new PublicKey($this->adapter, $this->senderKey->getPoint(), $this->secretKey); } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::setRecipientKey() */ public function setRecipientKey(PublicKeyInterface $key) { $this->recipientKey = $key; } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::setSenderKey() */ public function setSenderKey(PrivateKeyInterface $key) { $this->senderKey = $key; } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::encrypt() */ public function encrypt(Message $message) { $key = hash("sha256", $this->calculateSharedKey(), true); $cypherText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, base64_encode($message->getContent()), MCRYPT_MODE_CBC, $key); $message = $this->messages->ciphertext($cypherText); return $message; } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::decrypt() */ public function decrypt(EncryptedMessage $ciphertext) { $key = hash("sha256", $this->calculateSharedKey(), true); $clearText = base64_decode(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $ciphertext->getContent(), MCRYPT_MODE_CBC, $key)); $clearText = $this->messages->plaintext($clearText, 'sha256'); return $clearText; } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::encryptFile() */ public function encryptFile($path) { if (file_exists($path) && is_readable($path)) { $message = $this->messages->plaintext(file_get_contents($path), 'sha256'); return $this->encrypt($message); } throw new \InvalidArgumentException("File '$path' does not exist or is not readable."); } /** * {@inheritDoc} * @see \Mdanter\Ecc\Crypto\EcDH\EcDHInterface::decryptFile() */ public function decryptFile($path) { if (file_exists($path) && is_readable($path)) { $cipherText = $this->messages->ciphertext(file_get_contents($path)); return $cipherText; } throw new \InvalidArgumentException("File '$path' does not exist or is not readable."); } /** * */ private function calculateKey() { $this->checkExchangeState(); if ($this->secretKey === null) { $this->secretKey = $this->recipientKey->getPoint()->mul($this->senderKey->getSecret()); } } /** * Verifies that the shared secret is known, or that the required keys are available * to calculate the shared secret. * @throws \RuntimeException when the exchange has not been made. */ private function checkExchangeState() { if ($this->secretKey !== null) { return; } if ($this->senderKey === null) { throw new \RuntimeException('Sender key not set.'); } if ($this->recipientKey === null) { throw new \RuntimeException('Recipient key not set.'); } } }