diff --git a/src/Algorithm.php b/src/Algorithm.php index a3f6dc4..c01571b 100644 --- a/src/Algorithm.php +++ b/src/Algorithm.php @@ -18,6 +18,9 @@ abstract class Algorithm case 'hmac-sha256': return new HmacAlgorithm('sha256'); break; + case 'rsa-sha512': + return new RsaAlgorithm('sha512'); + break; default: throw new Exception("No algorithm named '$name'"); break; diff --git a/src/RsaAlgorithm.php b/src/RsaAlgorithm.php new file mode 100644 index 0000000..d9a5b8f --- /dev/null +++ b/src/RsaAlgorithm.php @@ -0,0 +1,64 @@ +digestName = $digestName; + } + + /** + * @return string + */ + public function name() + { + return sprintf('rsa-%s', $this->digestName); + } + + /** + * @param string $key + * @param string $data + * + * @return string + */ + public function sign($signingKey, $data) + { + $rsa = PublicKeyLoader::load($signingKey) + ->withHash($this->digestName) + ->withPadding(RSA::SIGNATURE_PKCS1); + $signature = $rsa->sign($data); + + return $signature; + } + + public function verify($message, $signature, $verifyingKey) + { + $rsa = PublicKeyLoader::load($verifyingKey) + ->withHash($this->digestName) + ->withPadding(RSA::SIGNATURE_PKCS1); + try { + $valid = $rsa->verify($message, base64_decode($signature)); + + return $valid; + } catch (\Exception $e) { + if ('Invalid signature' != $e->getMessage()) { + // Unhandled error state + throw $e; + } else { + // Tolerate malformed signature + return false; + } + } + } +}