/**
* Method to decrypt a data string.
*
* @param string $data The encrypted string to decrypt.
* @param Key $key The key object to use for decryption.
*
* @return string The decrypted data string.
*
* @since 3.8.0
* @throws \RuntimeException
*/
public function decrypt($data, Key $key)
{
// Validate key.
if ($key->getType() !== 'sodium') {
throw new \InvalidArgumentException('Invalid key of type: ' . $key->getType() . '. Expected sodium.');
}
if (!$this->nonce) {
throw new \RuntimeException('Missing nonce to decrypt data');
}
$decrypted = Compat::crypto_box_open($data, $this->nonce, Compat::crypto_box_keypair_from_secretkey_and_publickey($key->getPrivate(), $key->getPublic()));
if ($decrypted === false) {
throw new \RuntimeException('Malformed message or invalid MAC');
}
return $decrypted;
}