From 0f6e1c2218243eddff2cee2cc38bb189f938425a Mon Sep 17 00:00:00 2001 From: terrafrost Date: Sun, 5 Mar 2023 08:49:35 -0600 Subject: [PATCH] PKCS8: fix public private checks for human readable keys --- phpseclib/Crypt/Common/Formats/Keys/PKCS8.php | 14 +++++++++----- tests/Unit/Crypt/EC/KeyTest.php | 12 ++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/phpseclib/Crypt/Common/Formats/Keys/PKCS8.php b/phpseclib/Crypt/Common/Formats/Keys/PKCS8.php index 818f5a8f..4638a539 100644 --- a/phpseclib/Crypt/Common/Formats/Keys/PKCS8.php +++ b/phpseclib/Crypt/Common/Formats/Keys/PKCS8.php @@ -315,11 +315,15 @@ abstract class PKCS8 extends PKCS */ protected static function load($key, $password = '') { - $decoded = self::preParse($key); + if (!Strings::is_stringable($key)) { + throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key)); + } $isPublic = strpos($key, 'PUBLIC') !== false; $isPrivate = strpos($key, 'PRIVATE') !== false; + $decoded = self::preParse($key); + $meta = []; $decrypted = ASN1::asn1map($decoded[0], Maps\EncryptedPrivateKeyInfo::MAP); @@ -661,10 +665,6 @@ abstract class PKCS8 extends PKCS { self::initialize_static_variables(); - if (!Strings::is_stringable($key)) { - throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key)); - } - if (self::$format != self::MODE_DER) { $decoded = ASN1::extractBER($key); if ($decoded !== false) { @@ -690,6 +690,10 @@ abstract class PKCS8 extends PKCS */ public static function extractEncryptionAlgorithm($key) { + if (!Strings::is_stringable($key)) { + throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key)); + } + $decoded = self::preParse($key); $r = ASN1::asn1map($decoded[0], ASN1\Maps\EncryptedPrivateKeyInfo::MAP); diff --git a/tests/Unit/Crypt/EC/KeyTest.php b/tests/Unit/Crypt/EC/KeyTest.php index 43928d78..f0069a3a 100644 --- a/tests/Unit/Crypt/EC/KeyTest.php +++ b/tests/Unit/Crypt/EC/KeyTest.php @@ -678,4 +678,16 @@ MIIEDwIBADATBgcqhkjOPQIBBggqhkjOPQMBBwSCA/MwggPvAgEBBIID6P////// $key = PublicKeyLoader::load($key); $this->assertInstanceOf(PublicKey::class, $key); } + + public function testMislabledPKCS8PubKey() + { + $this->expectException('\phpseclib3\Exception\NoKeyLoadedException'); + + $key = '-----BEGIN PRIVATE KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErPJyxEu2/oKCrJaaTVTrq39DKJ2X +cN6W+k8UvGf+Y/lDWNbFitQocabsDUvSN0edHH3UKP5QPTz4cOlyIPMrXQ== +-----END PUBLIC KEY-----'; + $key = PublicKeyLoader::load($key); + $this->assertInstanceOf(PublicKey::class, $key); + } }