This commit is contained in:
Fred 2021-10-16 06:58:07 +08:00
parent cefeda7908
commit 9d452362de
2 changed files with 67 additions and 0 deletions

View File

@ -18,6 +18,9 @@ abstract class Algorithm
case 'hmac-sha256': case 'hmac-sha256':
return new HmacAlgorithm('sha256'); return new HmacAlgorithm('sha256');
break; break;
case 'rsa-sha512':
return new RsaAlgorithm('sha512');
break;
default: default:
throw new Exception("No algorithm named '$name'"); throw new Exception("No algorithm named '$name'");
break; break;

64
src/RsaAlgorithm.php Normal file
View File

@ -0,0 +1,64 @@
<?php
namespace HttpSignatures;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
class RsaAlgorithm implements AlgorithmInterface
{
/** @var string */
private $digestName;
/**
* @param string $digestName
*/
public function __construct($digestName)
{
$this->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;
}
}
}
}