ParagonIE\Halite\Asymmetric\Crypto::encrypt PHP Method

encrypt() public static method

Encrypt a string using asymmetric cryptography Wraps SymmetricCrypto::encrypt()
public static encrypt ( HiddenString $plaintext, EncryptionSecretKey $ourPrivateKey, EncryptionPublicKey $theirPublicKey, mixed $encoding = Halite::ENCODE_BASE64URLSAFE ) : string
$plaintext HiddenString The message to encrypt
$ourPrivateKey EncryptionSecretKey Our private key
$theirPublicKey EncryptionPublicKey Their public key
$encoding mixed Which encoding scheme to use?
return string Ciphertext
    public static function encrypt(HiddenString $plaintext, EncryptionSecretKey $ourPrivateKey, EncryptionPublicKey $theirPublicKey, $encoding = Halite::ENCODE_BASE64URLSAFE) : string
    {
        $sharedSecretKey = new EncryptionKey(self::getSharedSecret($ourPrivateKey, $theirPublicKey));
        $ciphertext = SymmetricCrypto::encrypt($plaintext, $sharedSecretKey, $encoding);
        unset($sharedSecretKey);
        return $ciphertext;
    }

Usage Example

 /**
  * @covers Asymmetric::encrypt()
  * @covers Asymmetric::decrypt()
  */
 public function testEncryptFail()
 {
     $alice = KeyFactory::generateEncryptionKeyPair();
     $bob = KeyFactory::generateEncryptionKeyPair();
     $message = Asymmetric::encrypt('test message', $alice->getSecretKey(), $bob->getPublicKey(), true);
     $r = \Sodium\randombytes_uniform(\mb_strlen($message, '8bit'));
     $amt = \Sodium\randombytes_uniform(8);
     $message[$r] = \chr(\ord($message[$r]) ^ 1 << $amt);
     try {
         $plain = Asymmetric::decrypt($message, $bob->getSecretKey(), $alice->getPublicKey(), true);
         $this->assertEquals($plain, $message);
         $this->fail('This should have thrown an InvalidMessage exception!');
     } catch (CryptoException\InvalidMessage $e) {
         $this->assertTrue($e instanceof CryptoException\InvalidMessage);
     }
 }
All Usage Examples Of ParagonIE\Halite\Asymmetric\Crypto::encrypt