Skip to content

Commit

Permalink
Fixes namshi#94
Browse files Browse the repository at this point in the history
  • Loading branch information
tillz authored Sep 29, 2016
1 parent d978cdb commit 524761e
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions src/Namshi/JOSE/Signer/OpenSSL/PublicKey.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php

namespace Namshi\JOSE\Signer\OpenSSL;
use phpseclib\File\ASN1;

use phpseclib\Math\BigInteger as BigInteger;
use InvalidArgumentException;
use Namshi\JOSE\Signer\SignerInterface;
use RuntimeException;
Expand All @@ -14,6 +16,18 @@ abstract class PublicKey implements SignerInterface
/**
* {@inheritdoc}
*/

private static $asn1Schema = [
'type' => ASN1::TYPE_SEQUENCE,
'children' => [
'r' => [
'type' => ASN1::TYPE_INTEGER,
],
's' => [
'type' => ASN1::TYPE_INTEGER,
],
],
];
public function sign($input, $key, $password = null)
{
$keyResource = $this->getKeyResource($key, $password);
Expand All @@ -23,7 +37,19 @@ public function sign($input, $key, $password = null)

$signature = null;
openssl_sign($input, $signature, $keyResource, $this->getHashingAlgorithm());

$asn1Decoder = new ASN1();

$asn1Decoded = $asn1Decoder->decodeBER($signature);
$asn1Decoded = $asn1Decoder->asn1map($asn1Decoded[0], self::$asn1Schema);
if( isset($asn1Decoded['r']) && isset($asn1Decoded['s']) &&
$asn1Decoded['r'] instanceof BigInteger &&
$asn1Decoded['s'] instanceof BigInteger ) {

$signature = $asn1Decoded['r']->toBytes().$asn1Decoded['s']->toBytes();
}else{
throw new RuntimeException('No Signature generated');
}
return $signature;
}

Expand All @@ -36,9 +62,12 @@ public function verify($key, $signature, $input)
if (!$this->supportsKey($keyResource)) {
throw new InvalidArgumentException('Invalid key supplied.');
}

$result = openssl_verify($input, $signature, $keyResource, $this->getHashingAlgorithm());

$asn1Encoder = new ASN1();
$asn1Encoded = $asn1Encoder->encodeDER( [
'r'=>new BigInteger(substr($signature,0,32), 256),
's'=>new BigInteger(substr($signature,32,32), 256)
], self::$asn1Schema);
$result = openssl_verify($input, $asn1Encoded, $keyResource, $this->getHashingAlgorithm());
if ($result === -1) {
throw new RuntimeException('Unknown error during verification.');
}
Expand Down

0 comments on commit 524761e

Please sign in to comment.