From 0086be8af1e5c9aef896d1355fd4b7ccd7fcdcdf Mon Sep 17 00:00:00 2001 From: terrafrost Date: Tue, 31 Oct 2023 08:41:17 -0500 Subject: [PATCH] EC/Signature/Format: add new IEEE format --- phpseclib/Crypt/EC/Formats/Signature/IEEE.php | 66 +++++++++++++++++++ tests/Unit/Crypt/EC/KeyTest.php | 14 ++++ 2 files changed, 80 insertions(+) create mode 100644 phpseclib/Crypt/EC/Formats/Signature/IEEE.php diff --git a/phpseclib/Crypt/EC/Formats/Signature/IEEE.php b/phpseclib/Crypt/EC/Formats/Signature/IEEE.php new file mode 100644 index 00000000..69139da4 --- /dev/null +++ b/phpseclib/Crypt/EC/Formats/Signature/IEEE.php @@ -0,0 +1,66 @@ + + * @copyright 2016 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +namespace phpseclib3\Crypt\EC\Formats\Signature; + +use phpseclib3\Math\BigInteger; + +/** + * ASN1 Signature Handler + * + * @author Jim Wigginton + */ +abstract class IEEE +{ + /** + * Loads a signature + * + * @param string $sig + * @return array + */ + public static function load($sig) + { + if (!is_string($sig)) { + return false; + } + + $len = strlen($sig); + if ($len & 1) { + return false; + } + + $r = new BigInteger(substr($sig, 0, $len >> 1), 256); + $s = new BigInteger(substr($sig, $len >> 1), 256); + + return compact('r', 's'); + } + + /** + * Returns a signature in the appropriate format + * + * @param \phpseclib3\Math\BigInteger $r + * @param \phpseclib3\Math\BigInteger $s + * @return string + */ + public static function save(BigInteger $r, BigInteger $s) + { + $r = $r->toBytes(); + $s = $s->toBytes(); + $len = max(strlen($r), strlen($s)); + return str_pad($r, $len, "\0", STR_PAD_LEFT) . str_pad($s, $len, "\0", STR_PAD_LEFT); + } +} diff --git a/tests/Unit/Crypt/EC/KeyTest.php b/tests/Unit/Crypt/EC/KeyTest.php index f0069a3a..bfd1724a 100644 --- a/tests/Unit/Crypt/EC/KeyTest.php +++ b/tests/Unit/Crypt/EC/KeyTest.php @@ -690,4 +690,18 @@ cN6W+k8UvGf+Y/lDWNbFitQocabsDUvSN0edHH3UKP5QPTz4cOlyIPMrXQ== $key = PublicKeyLoader::load($key); $this->assertInstanceOf(PublicKey::class, $key); } + + /** + * @group github1956 + */ + public function testIEEESignature() + { + $key = '{"alg":"ES256","crv":"P-256","ext":true,"key_ops":["verify"],"kty":"EC","x":"FKwqyGd4i2NAl8RUXCCBRCAIbcpeGyfyXwgA_AWHb8Y","y":"njxhw5O6zGVkBlcPDKYj0E-6VO1giHTUkJWBhgKNqd8"}'; + $key = PublicKeyLoader::load($key)->withSignatureFormat('IEEE')->withHash('sha384'); + + $signature = 'a4f61518323bac50b4f87a0f766ebb10d1db25358a0a20a98dab20be4e9c3be2d77ff5a8415cfce2967999c73d2a49b2d8c01990f72c04d99ebe3c4ebf75b4e9'; + $signature = pack('H*', $signature); + + $this->assertTrue($key->verify('hello world!', $signature)); + } }