/** * Check if the given digital signature belongs to the given message. * * You should be calling this function with a digital signature generated with * the generateDigitalSignature() function. * * Usage example (continuation of the generateDigitalSignature() example): * * <code> * //get the default public key * $pubKey = new PublicKey(); * * if (Cryptography::verifyDigitalSignature($pubKey, $message, $signature)) { * echo "the message was not modified"; * } else { * echo "the message have been modified"; * } * </code> * * @param PublicKey $key the public key associated with the private key used to generate the signature * @param string $message the message to be checked * @param string $signature the digital signature of the given message * * @return bool true if the message digitaly signed it equal to the digital signature * * @throws \InvalidArgumentException the given message or the given signature are not a valid string * @throws AsymmetricException the error occurred while checking the message */ public static function verifyDigitalSignature(PublicKey &$key, $message, $signature) { //check the message type if (!is_string($message) && strlen($message) <= 0) { throw new \InvalidArgumentException('The message to be checked must be a non-empty string'); } //check the message type if (!is_string($signature) && strlen($signature) <= 0) { throw new \InvalidArgumentException('The digital signature of the message must be a non-empty string'); } //check for the private key if (!$key->isLoaded()) { throw new AsymmetricException('It is impossible to generate a digital signature with an unloaded key', 13); } //get the signature result $binSignature = base64_decode($signature); //attempt to verify the digital signature $verificationResult = openssl_verify($message, $binSignature, $key()['key'], OPENSSL_ALGO_SHA256); //check for errors in the process if ($verificationResult !== 0 && $verificationResult !== 1) { throw new AsymmetricException('An unknown error has occurred while verifying the digital signature', 14); } //return the result return $verificationResult != 0; }