From 9d452362de1f04cc1c0dd2cafdf106f4da10f5d8 Mon Sep 17 00:00:00 2001 From: Fred Date: Sat, 16 Oct 2021 06:58:07 +0800 Subject: [PATCH] add RSA --- src/Algorithm.php | 3 +++ src/RsaAlgorithm.php | 64 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 src/RsaAlgorithm.php 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; + } + } + } +}