/** * Generate a digital signature for the given message. * * The digital signature can be used to authenticate the message because * a different message will produce a different digital signature. * * You will be using the public key corresponding to the given private key * to check the digital signature. * * Example usage: * <code> * $message = "who knows if this message will be modified....."; * * //get the default private key * $privKey = new PrivateKey(); * * //generate the digital signature * $signature = Cryptography::generateDigitalSignature($privKey, $message); * * //transmit the digital signature * </code> * * @param PrivateKey $key the priate key to be used to generate the message * @param string $message the message to be signed * * @return string the generate digital signature * * @throws \InvalidArgumentException the given message is not a valid string * @throws AsymmetricException the error occurred while generating the message */ public static function generateDigitalSignature(PrivateKey &$key, $message) { //check the message type if (!is_string($message) && strlen($message) <= 0) { throw new \InvalidArgumentException('The message to be signed 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', 11); } //get the managed version of the native key $managedKey = $key(); //generate the digital signature $digitalSignature = null; if (!openssl_sign($message, $digitalSignature, $managedKey['key'], 'sha256WithRSAEncryption')) { throw new AsymmetricException('It is impossible to generate the digital signature due to an unknown error', 12); } //return the signature in a binary-safe format return base64_encode($digitalSignature); }