diff --git a/src/JOSE/JWS.php b/src/JOSE/JWS.php index f6c3a86..604a288 100644 --- a/src/JOSE/JWS.php +++ b/src/JOSE/JWS.php @@ -39,9 +39,6 @@ function sign($private_key_or_secret, $algorithm = 'HS256') { $this->header['kid'] = $private_key_or_secret->components['kid']; } $this->signature = $this->_sign($private_key_or_secret); - if (!$this->signature) { - throw new JOSE_Exception('Signing failed because of unknown reason'); - } return $this; } @@ -69,25 +66,33 @@ private function rsa($public_or_private_key, $padding_mode) { } private function digest() { + $digest = ''; switch ($this->header['alg']) { case 'HS256': case 'RS256': case 'ES256': case 'PS256': - return 'sha256'; + $digest = 'sha256'; + break; case 'HS384': case 'RS384': case 'ES384': case 'PS384': - return 'sha384'; + $digest = 'sha384'; + break; case 'HS512': case 'RS512': case 'ES512': case 'PS512': - return 'sha512'; + $digest = 'sha512'; + break; default: throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm'); } + if(!in_array($digest, hash_algos())) { + throw new JOSE_Exception_UnexpectedAlgorithm(sprintf('Hashing algorithm %s does not exist', $this->header['alg'])); + } + return $digest; } private function _sign($private_key_or_secret) { @@ -95,6 +100,7 @@ private function _sign($private_key_or_secret) { $this->compact((object) $this->header), $this->compact((object) $this->claims) )); + switch ($this->header['alg']) { case 'HS256': case 'HS384': @@ -103,7 +109,11 @@ private function _sign($private_key_or_secret) { case 'RS256': case 'RS384': case 'RS512': - return $this->rsa($private_key_or_secret, RSA::SIGNATURE_PKCS1)->sign($signature_base_string); + $hash = $this->rsa($private_key_or_secret, RSA::SIGNATURE_PKCS1)->sign($signature_base_string); + if (!$hash) { + throw new JOSE_Exception('RSA signing failed because of unknown reason'); + } + return $hash; case 'ES256': case 'ES384': case 'ES512': diff --git a/test/JOSE/JWS_Test.php b/test/JOSE/JWS_Test.php index 1e2e13d..439a244 100644 --- a/test/JOSE/JWS_Test.php +++ b/test/JOSE/JWS_Test.php @@ -28,6 +28,12 @@ function testToJSONWithGeneralSyntax() { $this->assertEquals($expected, sprintf('%s', $jws->toJSON('general-syntax'))); } + function testSignBadAlgorithm() { + $jws = new JOSE_JWS($this->plain_jwt); + $this->setExpectedException('JOSE_Exception_UnexpectedAlgorithm'); + $jws = $jws->sign('shared-secret', 'blah'); + } + function testSignHS256() { $expected = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIifQ.jBKXM6zRu0nP2tYgNTgFxRDwKoiEbNl1P6GyXEHIwEw'; $jws = new JOSE_JWS($this->plain_jwt);