From 801ba41603f648e201f6bf378f2d7bee964df49b Mon Sep 17 00:00:00 2001 From: Ricardo Casallas Date: Fri, 22 Jul 2022 08:41:07 -0400 Subject: [PATCH 1/2] Crypto refactoring and ECKey usage distinction. --- .../tv-app/android/java/JNIDACProvider.cpp | 11 +- .../app/src/main/jni/cpp/JNIDACProvider.cpp | 11 +- .../credentials/TestHarnessDACProvider.cpp | 11 +- src/credentials/FabricTable.cpp | 10 +- .../TestOnlyLocalCertificateAuthority.h | 11 +- .../DeviceAttestationCredsExample.cpp | 11 +- .../tests/TestCertificationDeclaration.cpp | 8 +- src/credentials/tests/TestFabricTable.cpp | 24 +- src/crypto/CHIPCryptoPAL.h | 123 ++++-- src/crypto/CHIPCryptoPALOpenSSL.cpp | 9 +- src/crypto/CHIPCryptoPALmbedTLS.cpp | 390 +++++++++++++++++- src/crypto/hsm/CHIPCryptoPALHsm.h | 4 +- .../hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp | 8 + .../Framework/CHIP/MTRP256KeypairBridge.h | 2 + .../Framework/CHIP/MTRP256KeypairBridge.mm | 8 + .../EFR32/efr32-chip-mbedtls-config.h | 2 +- .../ESP32/ESP32FactoryDataProvider.cpp | 10 +- .../android/CHIPP256KeypairBridge.cpp | 8 + src/platform/android/CHIPP256KeypairBridge.h | 2 + .../nrfconnect/FactoryDataProvider.cpp | 2 +- .../secure_channel/tests/TestCASESession.cpp | 20 +- src/tools/chip-cert/Cmd_GenCD.cpp | 6 +- src/tools/chip-cert/KeyUtils.cpp | 12 +- 23 files changed, 568 insertions(+), 135 deletions(-) diff --git a/examples/tv-app/android/java/JNIDACProvider.cpp b/examples/tv-app/android/java/JNIDACProvider.cpp index 19fb4dd64da1c1..3b0e1effc017ca 100644 --- a/examples/tv-app/android/java/JNIDACProvider.cpp +++ b/examples/tv-app/android/java/JNIDACProvider.cpp @@ -135,14 +135,13 @@ CHIP_ERROR JNIDACProvider::GetProductAttestationIntermediateCert(MutableByteSpan return GetJavaByteByMethod(mGetProductAttestationIntermediateCertMethod, out_pai_buffer); } -// TODO: This should be moved to a method of P256Keypair CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) { - Crypto::P256SerializedKeypair serialized_keypair; - ReturnErrorOnFailure(serialized_keypair.SetLength(private_key.size() + public_key.size())); - memcpy(serialized_keypair.Bytes(), public_key.data(), public_key.size()); - memcpy(serialized_keypair.Bytes() + public_key.size(), private_key.data(), private_key.size()); - return keypair.Deserialize(serialized_keypair); + Crypto::P256PlaintextKeypair key_pair; + ReturnErrorOnFailure(key_pair.SetLength(private_key.size() + public_key.size())); + memcpy(key_pair.Bytes(), public_key.data(), public_key.size()); + memcpy(key_pair.Bytes() + public_key.size(), private_key.data(), private_key.size()); + return keypair.Initialize(key_pair); } CHIP_ERROR JNIDACProvider::SignWithDeviceAttestationKey(const ByteSpan & message_to_sign, MutableByteSpan & out_signature_buffer) diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp index 19fb4dd64da1c1..3b0e1effc017ca 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/JNIDACProvider.cpp @@ -135,14 +135,13 @@ CHIP_ERROR JNIDACProvider::GetProductAttestationIntermediateCert(MutableByteSpan return GetJavaByteByMethod(mGetProductAttestationIntermediateCertMethod, out_pai_buffer); } -// TODO: This should be moved to a method of P256Keypair CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) { - Crypto::P256SerializedKeypair serialized_keypair; - ReturnErrorOnFailure(serialized_keypair.SetLength(private_key.size() + public_key.size())); - memcpy(serialized_keypair.Bytes(), public_key.data(), public_key.size()); - memcpy(serialized_keypair.Bytes() + public_key.size(), private_key.data(), private_key.size()); - return keypair.Deserialize(serialized_keypair); + Crypto::P256PlaintextKeypair key_pair; + ReturnErrorOnFailure(key_pair.SetLength(private_key.size() + public_key.size())); + memcpy(key_pair.Bytes(), public_key.data(), public_key.size()); + memcpy(key_pair.Bytes() + public_key.size(), private_key.data(), private_key.size()); + return keypair.Initialize(key_pair); } CHIP_ERROR JNIDACProvider::SignWithDeviceAttestationKey(const ByteSpan & message_to_sign, MutableByteSpan & out_signature_buffer) diff --git a/src/app/tests/suites/credentials/TestHarnessDACProvider.cpp b/src/app/tests/suites/credentials/TestHarnessDACProvider.cpp index 1d8ef2461fd679..37db6b313f4f06 100644 --- a/src/app/tests/suites/credentials/TestHarnessDACProvider.cpp +++ b/src/app/tests/suites/credentials/TestHarnessDACProvider.cpp @@ -92,14 +92,13 @@ ByteSpan ReadValue(Json::Value jsonValue, uint8_t * buffer, size_t bufferLen) return ByteSpan(buffer, bytesLen); } -// TODO: This should be moved to a method of P256Keypair CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) { - Crypto::P256SerializedKeypair serialized_keypair; - ReturnErrorOnFailure(serialized_keypair.SetLength(private_key.size() + public_key.size())); - memcpy(serialized_keypair.Bytes(), public_key.data(), public_key.size()); - memcpy(serialized_keypair.Bytes() + public_key.size(), private_key.data(), private_key.size()); - return keypair.Deserialize(serialized_keypair); + Crypto::P256PlaintextKeypair key_pair; + ReturnErrorOnFailure(key_pair.SetLength(private_key.size() + public_key.size())); + memcpy(key_pair.Bytes(), public_key.data(), public_key.size()); + memcpy(key_pair.Bytes() + public_key.size(), private_key.data(), private_key.size()); + return keypair.Deserialize(key_pair); } } // namespace diff --git a/src/credentials/FabricTable.cpp b/src/credentials/FabricTable.cpp index 1829541e635e8a..2f6595fbf7b85b 100644 --- a/src/credentials/FabricTable.cpp +++ b/src/credentials/FabricTable.cpp @@ -677,16 +677,16 @@ CHIP_ERROR FabricTable::AddNewFabricForTest(const ByteSpan & rootCert, const Byt CHIP_ERROR err = CHIP_ERROR_INTERNAL; Crypto::P256Keypair injectedOpKey; - Crypto::P256SerializedKeypair injectedOpKeysSerialized; + Crypto::P256PlaintextKeypair injectedOpKeysPlaintext; Crypto::P256Keypair * opKey = nullptr; if (!opKeySpan.empty()) { - VerifyOrReturnError(opKeySpan.size() == injectedOpKeysSerialized.Capacity(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(opKeySpan.size() == injectedOpKeysPlaintext.Capacity(), CHIP_ERROR_INVALID_ARGUMENT); - memcpy(injectedOpKeysSerialized.Bytes(), opKeySpan.data(), opKeySpan.size()); - SuccessOrExit(err = injectedOpKeysSerialized.SetLength(opKeySpan.size())); - SuccessOrExit(err = injectedOpKey.Deserialize(injectedOpKeysSerialized)); + memcpy(injectedOpKeysPlaintext.Bytes(), opKeySpan.data(), opKeySpan.size()); + SuccessOrExit(err = injectedOpKeysPlaintext.SetLength(opKeySpan.size())); + SuccessOrExit(err = injectedOpKey.Initialize(injectedOpKeysPlaintext)); opKey = &injectedOpKey; } diff --git a/src/credentials/TestOnlyLocalCertificateAuthority.h b/src/credentials/TestOnlyLocalCertificateAuthority.h index e0fa13b5d12b48..dfbc02a0f1a175 100644 --- a/src/credentials/TestOnlyLocalCertificateAuthority.h +++ b/src/credentials/TestOnlyLocalCertificateAuthority.h @@ -56,11 +56,11 @@ class TestOnlyLocalCertificateAuthority TestOnlyLocalCertificateAuthority & Init() { - Crypto::P256SerializedKeypair emptyKeypair; + Crypto::P256PlaintextKeypair emptyKeypair; return Init(emptyKeypair); } - TestOnlyLocalCertificateAuthority & Init(Crypto::P256SerializedKeypair & rootKeyPair) + TestOnlyLocalCertificateAuthority & Init(Crypto::P256PlaintextKeypair & rootKeyPair) { SuccessOrExit(mCurrentStatus); @@ -69,13 +69,14 @@ class TestOnlyLocalCertificateAuthority if (rootKeyPair.Length() != 0) { - mCurrentStatus = mRootKeypair->Deserialize(rootKeyPair); - SuccessOrExit(mCurrentStatus); + mCurrentStatus = mRootKeypair->Initialize(rootKeyPair); } else { - mRootKeypair->Initialize(); + mCurrentStatus = mRootKeypair->Initialize(); } + SuccessOrExit(mCurrentStatus); + mCurrentStatus = GenerateRootCert(*mRootKeypair.get()); SuccessOrExit(mCurrentStatus); exit: diff --git a/src/credentials/examples/DeviceAttestationCredsExample.cpp b/src/credentials/examples/DeviceAttestationCredsExample.cpp index e96e36b59bd65b..d887b6266e6ba4 100644 --- a/src/credentials/examples/DeviceAttestationCredsExample.cpp +++ b/src/credentials/examples/DeviceAttestationCredsExample.cpp @@ -30,14 +30,13 @@ namespace Examples { namespace { -// TODO: This should be moved to a method of P256Keypair CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) { - Crypto::P256SerializedKeypair serialized_keypair; - ReturnErrorOnFailure(serialized_keypair.SetLength(private_key.size() + public_key.size())); - memcpy(serialized_keypair.Bytes(), public_key.data(), public_key.size()); - memcpy(serialized_keypair.Bytes() + public_key.size(), private_key.data(), private_key.size()); - return keypair.Deserialize(serialized_keypair); + Crypto::P256PlaintextKeypair key_pair; + ReturnErrorOnFailure(key_pair.SetLength(private_key.size() + public_key.size())); + memcpy(key_pair.Bytes(), public_key.data(), public_key.size()); + memcpy(key_pair.Bytes() + public_key.size(), private_key.data(), private_key.size()); + return keypair.Initialize(key_pair); } class ExampleDACProvider : public DeviceAttestationCredentialsProvider diff --git a/src/credentials/tests/TestCertificationDeclaration.cpp b/src/credentials/tests/TestCertificationDeclaration.cpp index cda5f90b05124e..ab318380002c90 100644 --- a/src/credentials/tests/TestCertificationDeclaration.cpp +++ b/src/credentials/tests/TestCertificationDeclaration.cpp @@ -270,12 +270,12 @@ static void TestCD_CMSSignAndVerify(nlTestSuite * inSuite, void * inContext) // Test with known key P256Keypair keypair2; - P256SerializedKeypair serializedKeypair; - memcpy(serializedKeypair, sTestCMS_SignerSerializedKeypair, sizeof(sTestCMS_SignerSerializedKeypair)); - serializedKeypair.SetLength(sizeof(sTestCMS_SignerSerializedKeypair)); + P256PlaintextKeypair plaintextKeypair; + memcpy(plaintextKeypair, sTestCMS_SignerSerializedKeypair, sizeof(sTestCMS_SignerSerializedKeypair)); + plaintextKeypair.SetLength(sizeof(sTestCMS_SignerSerializedKeypair)); cdContentIn = ByteSpan(sTestCMS_CDContent02); signedMessage = MutableByteSpan(signedMessageBuf); - NL_TEST_ASSERT(inSuite, keypair2.Deserialize(serializedKeypair) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, keypair2.Initialize(plaintextKeypair) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, CMS_Sign(cdContentIn, signerKeyId, keypair2, signedMessage) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, CMS_Verify(signedMessage, keypair2.Pubkey(), cdContentOut) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, cdContentIn.data_equal(cdContentOut)); diff --git a/src/credentials/tests/TestFabricTable.cpp b/src/credentials/tests/TestFabricTable.cpp index c0923279a0d1f9..36fda8c86a82f0 100644 --- a/src/credentials/tests/TestFabricTable.cpp +++ b/src/credentials/tests/TestFabricTable.cpp @@ -88,10 +88,10 @@ class ScopedFabricTable */ static CHIP_ERROR LoadTestFabric_Node01_01(nlTestSuite * inSuite, FabricTable & fabricTable, bool doCommit) { - Crypto::P256SerializedKeypair opKeysSerialized; + Crypto::P256PlaintextKeypair opKeys; FabricIndex fabricIndex; - memcpy((uint8_t *) (opKeysSerialized), TestCerts::sTestCert_Node01_01_PublicKey, TestCerts::sTestCert_Node01_01_PublicKey_Len); - memcpy((uint8_t *) (opKeysSerialized) + TestCerts::sTestCert_Node01_01_PublicKey_Len, TestCerts::sTestCert_Node01_01_PrivateKey, + memcpy((uint8_t *) (opKeys), TestCerts::sTestCert_Node01_01_PublicKey, TestCerts::sTestCert_Node01_01_PublicKey_Len); + memcpy((uint8_t *) (opKeys) + TestCerts::sTestCert_Node01_01_PublicKey_Len, TestCerts::sTestCert_Node01_01_PrivateKey, TestCerts::sTestCert_Node01_01_PrivateKey_Len); ByteSpan rcacSpan(TestCerts::sTestCert_Root01_Chip, TestCerts::sTestCert_Root01_Chip_Len); @@ -99,9 +99,9 @@ static CHIP_ERROR LoadTestFabric_Node01_01(nlTestSuite * inSuite, FabricTable & ByteSpan nocSpan(TestCerts::sTestCert_Node01_01_Chip, TestCerts::sTestCert_Node01_01_Chip_Len); NL_TEST_ASSERT(inSuite, - opKeysSerialized.SetLength(TestCerts::sTestCert_Node01_01_PublicKey_Len + - TestCerts::sTestCert_Node01_01_PrivateKey_Len) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, gFabric1OpKey.Deserialize(opKeysSerialized) == CHIP_NO_ERROR); + opKeys.SetLength(TestCerts::sTestCert_Node01_01_PublicKey_Len + TestCerts::sTestCert_Node01_01_PrivateKey_Len) == + CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, gFabric1OpKey.Initialize(opKeys) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, fabricTable.AddNewPendingTrustedRootCert(rcacSpan) == CHIP_NO_ERROR); @@ -123,10 +123,10 @@ static CHIP_ERROR LoadTestFabric_Node01_01(nlTestSuite * inSuite, FabricTable & */ static CHIP_ERROR LoadTestFabric_Node02_01(nlTestSuite * inSuite, FabricTable & fabricTable, bool doCommit) { - Crypto::P256SerializedKeypair opKeysSerialized; + Crypto::P256PlaintextKeypair opKeys; FabricIndex fabricIndex; - memcpy((uint8_t *) (opKeysSerialized), TestCerts::sTestCert_Node02_01_PublicKey, TestCerts::sTestCert_Node02_01_PublicKey_Len); - memcpy((uint8_t *) (opKeysSerialized) + TestCerts::sTestCert_Node02_01_PublicKey_Len, TestCerts::sTestCert_Node02_01_PrivateKey, + memcpy((uint8_t *) (opKeys), TestCerts::sTestCert_Node02_01_PublicKey, TestCerts::sTestCert_Node02_01_PublicKey_Len); + memcpy((uint8_t *) (opKeys) + TestCerts::sTestCert_Node02_01_PublicKey_Len, TestCerts::sTestCert_Node02_01_PrivateKey, TestCerts::sTestCert_Node02_01_PrivateKey_Len); ByteSpan rcacSpan(TestCerts::sTestCert_Root02_Chip, TestCerts::sTestCert_Root02_Chip_Len); @@ -134,9 +134,9 @@ static CHIP_ERROR LoadTestFabric_Node02_01(nlTestSuite * inSuite, FabricTable & ByteSpan nocSpan(TestCerts::sTestCert_Node02_01_Chip, TestCerts::sTestCert_Node02_01_Chip_Len); NL_TEST_ASSERT(inSuite, - opKeysSerialized.SetLength(TestCerts::sTestCert_Node02_01_PublicKey_Len + - TestCerts::sTestCert_Node02_01_PrivateKey_Len) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, gFabric2OpKey.Deserialize(opKeysSerialized) == CHIP_NO_ERROR); + opKeys.SetLength(TestCerts::sTestCert_Node02_01_PublicKey_Len + + TestCerts::sTestCert_Node02_01_PrivateKey_Len) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, gFabric2OpKey.Initialize(opKeys) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, fabricTable.AddNewPendingTrustedRootCert(rcacSpan) == CHIP_NO_ERROR); diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index 58d4845567dc61..11b103583ac597 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -75,10 +75,16 @@ constexpr uint32_t kSpake2p_Max_PBKDF_Iterations = 100000; constexpr size_t kP256_PrivateKey_Length = CHIP_CRYPTO_GROUP_SIZE_BYTES; constexpr size_t kP256_PublicKey_Length = CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES; +constexpr size_t kMax_SerializeKey_Length = kP256_PublicKey_Length + kP256_PrivateKey_Length; +constexpr size_t kMax_PlaintextKey_Length = kP256_PublicKey_Length + kP256_PrivateKey_Length; constexpr size_t kAES_CCM128_Key_Length = 128u / 8u; constexpr size_t kAES_CCM128_Block_Length = kAES_CCM128_Key_Length; +// TODO: Remove AES-256 from CryptoPAL since not required by V1 spec +constexpr size_t kAES_CCM256_Key_Length = 256u / 8u; +constexpr size_t kAES_CCM256_Block_Length = kAES_CCM256_Key_Length; + /* These sizes are hardcoded here to remove header dependency on underlying crypto library * in a public interface file. The validity of these sizes is verified by static_assert in * the implementation files. @@ -163,7 +169,7 @@ enum class CHIP_SPAKE2P_ROLE : uint8_t PROVER = 1, // Commissioner }; -enum class SupportedECPKeyTypes : uint8_t +enum class SupportedECKeyTypes : uint8_t { ECP256R1 = 0, }; @@ -197,11 +203,11 @@ void ClearSecretData(uint8_t (&buf)[N]) bool IsBufferContentEqualConstantTime(const void * a, const void * b, size_t n); template -class ECPKey +class ECPublicKey { public: - virtual ~ECPKey() {} - virtual SupportedECPKeyTypes Type() const = 0; + virtual ~ECPublicKey() {} + virtual SupportedECKeyTypes Type() const = 0; virtual size_t Length() const = 0; virtual bool IsUncompressed() const = 0; virtual operator const uint8_t *() const = 0; @@ -209,7 +215,7 @@ class ECPKey virtual const uint8_t * ConstBytes() const = 0; virtual uint8_t * Bytes() = 0; - virtual bool Matches(const ECPKey & other) const + virtual bool Matches(const ECPublicKey & other) const { return (this->Length() == other.Length()) && IsBufferContentEqualConstantTime(this->ConstBytes(), other.ConstBytes(), this->Length()); @@ -283,7 +289,11 @@ typedef CapacityBoundBuffer P256ECDSASignature; typedef CapacityBoundBuffer P256ECDHDerivedSecret; -class P256PublicKey : public ECPKey +typedef CapacityBoundBuffer P256SerializedKeypair; + +typedef CapacityBoundBuffer P256PlaintextKeypair; + +class P256PublicKey : public ECPublicKey { public: P256PublicKey() {} @@ -310,7 +320,7 @@ class P256PublicKey : public ECPKey return *this; } - SupportedECPKeyTypes Type() const override { return SupportedECPKeyTypes::ECP256R1; } + SupportedECKeyTypes Type() const override { return SupportedECKeyTypes::ECP256R1; } size_t Length() const override { return kP256_PublicKey_Length; } operator uint8_t *() override { return bytes; } operator const uint8_t *() const override { return bytes; } @@ -333,11 +343,48 @@ class P256PublicKey : public ECPKey uint8_t bytes[kP256_PublicKey_Length]; }; -template -class ECPKeypair +template +class ECKeypair { public: - virtual ~ECPKeypair() {} + virtual ~ECKeypair() {} + + /** + * @brief Initialize the keypair. + * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise + **/ + virtual CHIP_ERROR Initialize() = 0; + + /** + * @brief Initialize the keypair by importing a plaintext key. + * + * This function takes a key in plaintext format to initialize + * the keypair object. Multiple keys can be instantiated from the + * same plaintext bytes. + * + * The plaintext format is defined as the binary concatenation of + * the public key and the private key, both in uncompressed form. + * For a key on the P256 curve, this means the plaintext key starts + * with a byte set to 0x04, followed by 32 bytes of public key X-coordinate, + * followed by 32 bytes of public key Y-coordinate, followed by + * 32 bytes of private key (all MSB first and zero-extended to + * the left if necessary). + * + * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise + **/ + virtual CHIP_ERROR Initialize(Plaintext & input) = 0; + + /** + * @brief Serialize the keypair. + * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise + **/ + virtual CHIP_ERROR Serialize(Serialized & output) const = 0; + + /** + * @brief Deserialize the keypair. + * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise + **/ + virtual CHIP_ERROR Deserialize(Serialized & input) = 0; /** @brief Generate a new Certificate Signing Request (CSR). * @param csr Newly generated CSR in DER format @@ -367,6 +414,13 @@ class ECPKeypair virtual CHIP_ERROR ECDH_derive_secret(const PK & remote_public_key, Secret & out_secret) const = 0; virtual const PK & Pubkey() const = 0; + + /** Release resources associated with this key pair */ + virtual void Clear() = 0; + +protected: + bool mInitialized = false; + PK mPublicKey; }; struct alignas(size_t) P256KeypairContext @@ -374,41 +428,38 @@ struct alignas(size_t) P256KeypairContext uint8_t mBytes[kMAX_P256Keypair_Context_Size]; }; -typedef CapacityBoundBuffer P256SerializedKeypair; - -class P256KeypairBase : public ECPKeypair +class P256Keypair + : public ECKeypair { public: - /** - * @brief Initialize the keypair. - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - virtual CHIP_ERROR Initialize() = 0; + P256Keypair() {} - /** - * @brief Serialize the keypair. - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - virtual CHIP_ERROR Serialize(P256SerializedKeypair & output) const = 0; + ~P256Keypair() override; /** - * @brief Deserialize the keypair. + * @brief Initialize the keypair by generating a new key. * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - virtual CHIP_ERROR Deserialize(P256SerializedKeypair & input) = 0; -}; - -class P256Keypair : public P256KeypairBase -{ -public: - P256Keypair() {} - ~P256Keypair() override; + CHIP_ERROR Initialize() override; /** - * @brief Initialize the keypair. + * @brief Initialize the keypair by importing a plaintext key. + * + * This function takes a key in plaintext format to initialize + * the keypair object. Multiple keys can be instantiated from the + * same plaintext bytes. + * + * The plaintext format is defined as the binary concatenation of + * the public key and the private key, both in uncompressed form. + * For a key on the P256 curve, this means the plaintext key starts + * with a byte set to 0x04, followed by 32 bytes of public key X-coordinate, + * followed by 32 bytes of public key Y-coordinate, followed by + * 32 bytes of private key (all MSB first and zero-extended to + * the left if necessary). + * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR Initialize() override; + CHIP_ERROR Initialize(P256PlaintextKeypair & input) override; /** * @brief Serialize the keypair. @@ -461,12 +512,10 @@ class P256Keypair : public P256KeypairBase const P256PublicKey & Pubkey() const override { return mPublicKey; } /** Release resources associated with this key pair */ - void Clear(); + void Clear() override; private: - P256PublicKey mPublicKey; mutable P256KeypairContext mKeypair; - bool mInitialized = false; }; /** diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index 0eb2f4687e3a12..cf604cd71d2693 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -654,7 +654,7 @@ CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length) return CHIP_NO_ERROR; } -ECName MapECName(SupportedECPKeyTypes keyType) +ECName MapECName(SupportedECKeyTypes keyType) { switch (keyType) { @@ -1056,6 +1056,13 @@ CHIP_ERROR P256Keypair::Initialize() return error; } +CHIP_ERROR P256Keypair::Initialize(P256PlaintextKeypair & input) +{ + // For crypto libraries who don't manage keys, plaintext and serialised + // format is the same. + return Deserialize(static_cast(input)); +} + CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const { CHIP_ERROR error = CHIP_NO_ERROR; diff --git a/src/crypto/CHIPCryptoPALmbedTLS.cpp b/src/crypto/CHIPCryptoPALmbedTLS.cpp index 59b11d1e34a681..3420a018826362 100644 --- a/src/crypto/CHIPCryptoPALmbedTLS.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLS.cpp @@ -44,6 +44,13 @@ #include #include +#if defined(MBEDTLS_USE_TINYCRYPT) +#include +#include +#include +#include +#endif // defined(MBEDTLS_USE_TINYCRYPT) + #include #include #include @@ -86,7 +93,11 @@ static EntropyContext gsEntropyContext; static void _log_mbedTLS_error(int error_code) { +#if defined(MBEDTLS_USE_TINYCRYPT) + if (error_code != 0 && error_code != UECC_SUCCESS) +#else if (error_code != 0) +#endif { #if defined(MBEDTLS_ERROR_C) char error_str[MAX_ERROR_STR_LEN]; @@ -485,17 +496,49 @@ static int CryptoRNG(void * ctxt, uint8_t * out_buffer, size_t out_length) return (chip::Crypto::DRBG_get_bytes(out_buffer, out_length) == CHIP_NO_ERROR) ? 0 : 1; } -mbedtls_ecp_group_id MapECPGroupId(SupportedECPKeyTypes keyType) +#if defined(MBEDTLS_USE_TINYCRYPT) + +static int uecc_rng_wrapper(uint8_t * dest, unsigned int size) +{ + int ret; + + ret = CryptoRNG(NULL, dest, size); + + return (ret == 0) ? size : 0; +} + +static int uECC_is_rng_set(void) +{ + return (uecc_rng_wrapper == uECC_get_rng()) ? 1 : 0; +} + +#endif + +mbedtls_ecp_group_id MapECPGroupId(SupportedECKeyTypes keyType) { switch (keyType) { - case SupportedECPKeyTypes::ECP256R1: + case SupportedECKeyTypes::ECP256R1: return MBEDTLS_ECP_DP_SECP256R1; default: return MBEDTLS_ECP_DP_NONE; } } +#if defined(MBEDTLS_USE_TINYCRYPT) + +static inline mbedtls_uecc_keypair * to_keypair(P256KeypairContext * context) +{ + return SafePointerCast(context); +} + +static inline const mbedtls_uecc_keypair * to_const_keypair(const P256KeypairContext * context) +{ + return SafePointerCast(context); +} + +#else + static inline mbedtls_ecp_keypair * to_keypair(P256KeypairContext * context) { return SafePointerCast(context); @@ -506,6 +549,8 @@ static inline const mbedtls_ecp_keypair * to_const_keypair(const P256KeypairCont return SafePointerCast(context); } +#endif + CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, const size_t msg_length, P256ECDSASignature & out_signature) const { VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE); @@ -515,9 +560,24 @@ CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, const size_t msg_len memset(&digest[0], 0, sizeof(digest)); ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0])); -#if defined(MBEDTLS_ECDSA_C) +#if defined(MBEDTLS_USE_TINYCRYPT) CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; + int result = UECC_FAILURE; + + const mbedtls_uecc_keypair * keypair = to_const_keypair(&mKeypair); + + result = uECC_sign(keypair->private_key, digest, sizeof(digest), out_signature.Bytes()); + + VerifyOrExit(result == UECC_SUCCESS, error = CHIP_ERROR_INTERNAL); + VerifyOrExit(out_signature.SetLength(kP256_ECDSA_Signature_Length_Raw) == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + + keypair = nullptr; + +exit: + return error; +#elif defined(MBEDTLS_ECDSA_C) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; mbedtls_mpi r, s; mbedtls_mpi_init(&r); mbedtls_mpi_init(&s); @@ -578,13 +638,29 @@ CHIP_ERROR P256PublicKey::ECDSA_validate_msg_signature(const uint8_t * msg, cons CHIP_ERROR P256PublicKey::ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length, const P256ECDSASignature & signature) const { -#if defined(MBEDTLS_ECDSA_C) +#if defined(MBEDTLS_USE_TINYCRYPT) VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(signature.Length() == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; + int result = UECC_FAILURE; + + const uint8_t * public_key = *this; + + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + result = uECC_verify(public_key + 1, hash, hash_length, Uint8::to_const_uchar(signature.ConstBytes())); + VerifyOrExit(result == UECC_SUCCESS, error = CHIP_ERROR_INVALID_SIGNATURE); + +exit: + return error; +#elif defined(MBEDTLS_ECDSA_C) + VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(signature.Length() == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INVALID_ARGUMENT); + + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; mbedtls_mpi r, s; mbedtls_mpi_init(&r); @@ -636,6 +712,26 @@ CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_k { #if defined(MBEDTLS_ECDH_C) +#if defined(MBEDTLS_USE_TINYCRYPT) + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); + + const mbedtls_uecc_keypair * keypair = to_const_keypair(&mKeypair); + + VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE); + + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + result = uECC_shared_secret(remote_public_key.ConstBytes() + 1, keypair->private_key, Uint8::to_uchar(out_secret)); + VerifyOrExit(result == UECC_SUCCESS, error = CHIP_ERROR_INTERNAL); + + SuccessOrExit(out_secret.SetLength(secret_length)); + +exit: + keypair = nullptr; + _log_mbedTLS_error(result); + return error; +#else CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); @@ -675,6 +771,7 @@ CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_k mbedtls_ecp_point_free(&ecp_pubkey); _log_mbedTLS_error(result); return error; +#endif #else return CHIP_ERROR_NOT_IMPLEMENTED; @@ -714,8 +811,34 @@ bool IsBufferContentEqualConstantTime(const void * a, const void * b, size_t n) CHIP_ERROR P256Keypair::Initialize() { +#if defined(MBEDTLS_USE_TINYCRYPT) CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; + int result = UECC_FAILURE; + + Clear(); + + mbedtls_uecc_keypair * keypair = to_keypair(&mKeypair); + if (!uECC_is_rng_set()) + { + uECC_set_rng(&uecc_rng_wrapper); + } + + result = uECC_make_key(keypair->public_key, keypair->private_key); + VerifyOrExit(result == UECC_SUCCESS, error = CHIP_ERROR_INTERNAL); + + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + Uint8::to_uchar(mPublicKey)[0] = 0x04; + memcpy(Uint8::to_uchar(mPublicKey) + 1, keypair->public_key, 2 * NUM_ECC_BYTES); + + keypair = nullptr; + mInitialized = true; + +exit: + _log_mbedTLS_error(result); + return error; +#else + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; size_t pubkey_size = 0; @@ -735,7 +858,7 @@ CHIP_ERROR P256Keypair::Initialize() VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(pubkey_size == mPublicKey.Length(), error = CHIP_ERROR_INVALID_ARGUMENT); - keypair = nullptr; + keypair = nullptr; mInitialized = true; exit: @@ -747,12 +870,21 @@ CHIP_ERROR P256Keypair::Initialize() _log_mbedTLS_error(result); return error; +#endif +} + +CHIP_ERROR P256Keypair::Initialize(P256PlaintextKeypair & input) +{ + // For crypto libraries who don't manage keys, plaintext and serialised + // format is the same. + return Deserialize(static_cast(input)); } CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const { - const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); - size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); +#if defined(MBEDTLS_USE_TINYCRYPT) + const mbedtls_uecc_keypair * keypair = to_const_keypair(&mKeypair); + size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); Encoding::BufferWriter bbuf(output, len); uint8_t privkey[kP256_PrivateKey_Length]; CHIP_ERROR error = CHIP_NO_ERROR; @@ -760,6 +892,30 @@ CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const bbuf.Put(mPublicKey, mPublicKey.Length()); + VerifyOrExit(bbuf.Available() == sizeof(privkey), error = CHIP_ERROR_INTERNAL); + VerifyOrExit(sizeof(keypair->private_key) <= bbuf.Available(), error = CHIP_ERROR_INTERNAL); + + memcpy(privkey, keypair->private_key, sizeof(privkey)); + + bbuf.Put(privkey, sizeof(privkey)); + VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + + output.SetLength(bbuf.Needed()); + +exit: + memset(privkey, 0, sizeof(privkey)); + _log_mbedTLS_error(result); + return error; +#else + const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); + size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); + Encoding::BufferWriter bbuf(output, len); + uint8_t privkey[kP256_PrivateKey_Length]; + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + + bbuf.Put(mPublicKey, mPublicKey.Length()); + VerifyOrExit(bbuf.Available() == sizeof(privkey), error = CHIP_ERROR_INTERNAL); VerifyOrExit(mbedtls_mpi_size(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d)) <= bbuf.Available(), error = CHIP_ERROR_INTERNAL); @@ -776,13 +932,44 @@ CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const ClearSecretData(privkey, sizeof(privkey)); _log_mbedTLS_error(result); return error; +#endif } CHIP_ERROR P256Keypair::Deserialize(P256SerializedKeypair & input) { +#if defined(MBEDTLS_USE_TINYCRYPT) + int result = 0; + CHIP_ERROR error = CHIP_NO_ERROR; Encoding::BufferWriter bbuf(mPublicKey, mPublicKey.Length()); - int result = 0; + Clear(); + + mbedtls_uecc_keypair * keypair = to_keypair(&mKeypair); + if (!uECC_is_rng_set()) + { + uECC_set_rng(&uecc_rng_wrapper); + } + + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + memcpy(keypair->public_key, Uint8::to_uchar(input) + 1, 2 * NUM_ECC_BYTES); + memcpy(keypair->private_key, Uint8::to_uchar(input) + mPublicKey.Length(), NUM_ECC_BYTES); + + keypair = nullptr; + + VerifyOrExit(input.Length() == mPublicKey.Length() + kP256_PrivateKey_Length, error = CHIP_ERROR_INVALID_ARGUMENT); + bbuf.Put((const uint8_t *) input, mPublicKey.Length()); + VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_NO_MEMORY); + + mInitialized = true; + + _log_mbedTLS_error(result); + +exit: + return error; +#else + Encoding::BufferWriter bbuf(mPublicKey, mPublicKey.Length()); + + int result = 0; CHIP_ERROR error = CHIP_NO_ERROR; Clear(); @@ -813,15 +1000,22 @@ CHIP_ERROR P256Keypair::Deserialize(P256SerializedKeypair & input) exit: _log_mbedTLS_error(result); return error; +#endif } void P256Keypair::Clear() { if (mInitialized) { +#if defined(MBEDTLS_USE_TINYCRYPT) + mbedtls_uecc_keypair * keypair = to_keypair(&mKeypair); + memset(keypair, 0, sizeof(mbedtls_uecc_keypair)); + mInitialized = false; +#else mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_free(keypair); mInitialized = false; +#endif } } @@ -947,8 +1141,21 @@ CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr_buf, size_t csr_l typedef struct Spake2p_Context { +#if defined(MBEDTLS_USE_TINYCRYPT) + uECC_word_t M[2 * NUM_ECC_WORDS]; + uECC_word_t N[2 * NUM_ECC_WORDS]; + uECC_word_t X[2 * NUM_ECC_WORDS]; + uECC_word_t Y[2 * NUM_ECC_WORDS]; + uECC_word_t L[2 * NUM_ECC_WORDS]; + uECC_word_t Z[2 * NUM_ECC_WORDS]; + uECC_word_t V[2 * NUM_ECC_WORDS]; + + uECC_word_t w0[NUM_ECC_WORDS]; + uECC_word_t w1[NUM_ECC_WORDS]; + uECC_word_t xy[NUM_ECC_WORDS]; + uECC_word_t tempbn[NUM_ECC_WORDS]; +#else mbedtls_ecp_group curve; - const mbedtls_md_info_t * md_info; mbedtls_ecp_point M; mbedtls_ecp_point N; mbedtls_ecp_point X; @@ -961,6 +1168,7 @@ typedef struct Spake2p_Context mbedtls_mpi w1; mbedtls_mpi xy; mbedtls_mpi tempbn; +#endif } Spake2p_Context; static inline Spake2p_Context * to_inner_spake2p_context(Spake2pOpaqueContext * context) @@ -977,12 +1185,32 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal(void) memset(context, 0, sizeof(Spake2p_Context)); +#if defined(MBEDTLS_USE_TINYCRYPT) + M = context->M; + N = context->N; + X = context->X; + Y = context->Y; + L = context->L; + V = context->V; + Z = context->Z; + + w0 = context->w0; + w1 = context->w1; + xy = context->xy; + tempbn = context->tempbn; + + G = curve_G; + + if (!uECC_is_rng_set()) + { + uECC_set_rng(&uecc_rng_wrapper); + } +#else mbedtls_ecp_group_init(&context->curve); result = mbedtls_ecp_group_load(&context->curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - context->md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); - VerifyOrExit(context->md_info != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrExit(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256) != nullptr, error = CHIP_ERROR_INTERNAL); mbedtls_ecp_point_init(&context->M); mbedtls_ecp_point_init(&context->N); @@ -1003,13 +1231,14 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal(void) mbedtls_mpi_init(&context->w1); mbedtls_mpi_init(&context->xy); mbedtls_mpi_init(&context->tempbn); - w0 = &context->w0; - w1 = &context->w1; - xy = &context->xy; + w0 = &context->w0; + w1 = &context->w1; + xy = &context->xy; tempbn = &context->tempbn; - G = &context->curve.G; + G = &context->curve.G; order = &context->curve.N; +#endif return error; @@ -1024,6 +1253,22 @@ void Spake2p_P256_SHA256_HKDF_HMAC::Clear() VerifyOrReturn(state != CHIP_SPAKE2P_STATE::PREINIT); Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); +#if defined(MBEDTLS_USE_TINYCRYPT) + memset(&context->M, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->N, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->X, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->Y, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->L, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->Z, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->V, 0, 2 * NUM_ECC_WORDS * sizeof(uECC_word_t)); + + memset(&context->w0, 0, NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->w1, 0, NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->xy, 0, NUM_ECC_WORDS * sizeof(uECC_word_t)); + memset(&context->tempbn, 0, NUM_ECC_WORDS * sizeof(uECC_word_t)); + + G = NULL; +#else mbedtls_ecp_point_free(&context->M); mbedtls_ecp_point_free(&context->N); mbedtls_ecp_point_free(&context->X); @@ -1038,6 +1283,7 @@ void Spake2p_P256_SHA256_HKDF_HMAC::Clear() mbedtls_mpi_free(&context->tempbn); mbedtls_ecp_group_free(&context->curve); +#endif state = CHIP_SPAKE2P_STATE::PREINIT; } @@ -1076,11 +1322,18 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FELoad(const uint8_t * in, size_t in_l CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; +#if defined(MBEDTLS_USE_TINYCRYPT) + uECC_word_t tmp[2 * NUM_ECC_WORDS] = { 0 }; + uECC_vli_bytesToNative(tmp, in, NUM_ECC_BYTES); + + uECC_vli_mmod((uECC_word_t *) fe, tmp, curve_n); +#else result = mbedtls_mpi_read_binary((mbedtls_mpi *) fe, Uint8::to_const_uchar(in), in_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fe, (mbedtls_mpi *) fe, (const mbedtls_mpi *) order); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); +#endif exit: _log_mbedTLS_error(result); @@ -1089,10 +1342,14 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FELoad(const uint8_t * in, size_t in_l CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEWrite(const void * fe, uint8_t * out, size_t out_len) { +#if defined(MBEDTLS_USE_TINYCRYPT) + uECC_vli_nativeToBytes(out, NUM_ECC_BYTES, (const unsigned int *) fe); +#else if (mbedtls_mpi_write_binary((const mbedtls_mpi *) fe, Uint8::to_uchar(out), out_len) != 0) { return CHIP_ERROR_INTERNAL; } +#endif return CHIP_NO_ERROR; } @@ -1101,10 +1358,21 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEGenerate(void * fe) CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; +#if defined(MBEDTLS_USE_TINYCRYPT) + mbedtls_uecc_keypair keypair; + + result = UECC_FAILURE; + + result = uECC_make_key(keypair.public_key, keypair.private_key); + VerifyOrExit(result == UECC_SUCCESS, error = CHIP_ERROR_INTERNAL); + + uECC_vli_bytesToNative((uECC_word_t *) fe, keypair.private_key, NUM_ECC_BYTES); +#else Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); result = mbedtls_ecp_gen_privkey(&context->curve, (mbedtls_mpi *) fe, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); +#endif exit: _log_mbedTLS_error(result); @@ -1116,11 +1384,15 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEMul(void * fer, const void * fe1, co CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; +#if defined(MBEDTLS_USE_TINYCRYPT) + uECC_vli_modMult((uECC_word_t *) fer, (const uECC_word_t *) fe1, (const uECC_word_t *) fe2, (const uECC_word_t *) curve_n); +#else result = mbedtls_mpi_mul_mpi((mbedtls_mpi *) fer, (const mbedtls_mpi *) fe1, (const mbedtls_mpi *) fe2); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fer, (mbedtls_mpi *) fer, (const mbedtls_mpi *) order); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); +#endif exit: _log_mbedTLS_error(result); @@ -1129,12 +1401,22 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEMul(void * fer, const void * fe1, co CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointLoad(const uint8_t * in, size_t in_len, void * R) { +#if defined(MBEDTLS_USE_TINYCRYPT) + uint8_t tmp[2 * NUM_ECC_BYTES]; + + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + memcpy(tmp, in + 1, 2 * NUM_ECC_BYTES); + + uECC_vli_bytesToNative((uECC_word_t *) R, tmp, NUM_ECC_BYTES); + uECC_vli_bytesToNative((uECC_word_t *) R + NUM_ECC_WORDS, tmp + NUM_ECC_BYTES, NUM_ECC_BYTES); +#else Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_point_read_binary(&context->curve, (mbedtls_ecp_point *) R, Uint8::to_const_uchar(in), in_len) != 0) { return CHIP_ERROR_INTERNAL; } +#endif return CHIP_NO_ERROR; } @@ -1143,6 +1425,12 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointWrite(const void * R, uint8_t * o { memset(out, 0, out_len); +#if defined(MBEDTLS_USE_TINYCRYPT) + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + out[0] = 0x04; + uECC_vli_nativeToBytes(out + 1, NUM_ECC_BYTES, (uECC_word_t *) R); + uECC_vli_nativeToBytes(out + NUM_ECC_BYTES + 1, NUM_ECC_BYTES, (uECC_word_t *) R + NUM_ECC_WORDS); +#else size_t mbedtls_out_len = out_len; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); @@ -1152,16 +1440,22 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointWrite(const void * R, uint8_t * o { return CHIP_ERROR_INTERNAL; } +#endif return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointMul(void * R, const void * P1, const void * fe1) { + +#if defined(MBEDTLS_USE_TINYCRYPT) + if (EccPoint_mult_safer((uECC_word_t *) R, (const uECC_word_t *) P1, (const uECC_word_t *) fe1) != UECC_SUCCESS) +#else Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_mul(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, CryptoRNG, nullptr) != 0) +#endif { return CHIP_ERROR_INTERNAL; } @@ -1172,6 +1466,29 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointMul(void * R, const void * P1, co CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, const void * fe2) { +#if defined(MBEDTLS_USE_TINYCRYPT) + uECC_word_t R1[2 * NUM_ECC_WORDS]; + uECC_word_t R2[2 * NUM_ECC_WORDS]; + uECC_word_t z[NUM_ECC_WORDS]; + uint8_t ret = UECC_SUCCESS; + + if (EccPoint_mult_safer(R1, (const uECC_word_t *) P1, (const uECC_word_t *) fe1) != UECC_SUCCESS) + { + return CHIP_ERROR_INTERNAL; + } + + if (EccPoint_mult_safer(R2, (const uECC_word_t *) P2, (const uECC_word_t *) fe2) != UECC_SUCCESS) + { + return CHIP_ERROR_INTERNAL; + } + + uECC_vli_modSub(z, R2, R1, curve_p); + XYcZ_add(R1, R1 + NUM_ECC_WORDS, R2, R2 + NUM_ECC_WORDS); + uECC_vli_modInv(z, z, curve_p); + apply_z(R2, R2 + NUM_ECC_WORDS, z); + + memcpy((uECC_word_t *) R, R2, 2 * NUM_ECC_BYTES); +#else Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_muladd(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, @@ -1179,19 +1496,27 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, { return CHIP_ERROR_INTERNAL; } +#endif return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointInvert(void * R) { - mbedtls_ecp_point * Rp = (mbedtls_ecp_point *) R; +#if defined(MBEDTLS_USE_TINYCRYPT) + uECC_word_t tmp[NUM_ECC_WORDS] = { 0 }; + + uECC_vli_sub(tmp, curve_p, (uECC_word_t *) R + NUM_ECC_WORDS); + memcpy((uECC_word_t *) R + NUM_ECC_WORDS, tmp, NUM_ECC_BYTES); +#else + mbedtls_ecp_point * Rp = (mbedtls_ecp_point *) R; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_mpi_sub_mpi(&Rp->CHIP_CRYPTO_PAL_PRIVATE(Y), &context->curve.P, &Rp->CHIP_CRYPTO_PAL_PRIVATE(Y)) != 0) { return CHIP_ERROR_INTERNAL; } +#endif return CHIP_NO_ERROR; } @@ -1206,6 +1531,24 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; +#if defined(MBEDTLS_USE_TINYCRYPT) + result = UECC_SUCCESS; + uECC_word_t tmp[2 * NUM_ECC_WORDS]; + uECC_word_t w1_bn[NUM_ECC_WORDS]; + uECC_word_t L_tmp[2 * NUM_ECC_WORDS]; + + uECC_vli_bytesToNative(tmp, w1in, NUM_ECC_BYTES); + + uECC_vli_mmod(w1_bn, tmp, curve_n); + + result = EccPoint_mult_safer(L_tmp, curve_G, w1_bn); + VerifyOrExit(result == UECC_SUCCESS, error = CHIP_ERROR_INTERNAL); + + // Fully padded raw uncompressed points expected, first byte is always 0x04 i.e uncompressed + Lout[0] = 0x04; + uECC_vli_nativeToBytes(Lout + 1, NUM_ECC_BYTES, L_tmp); + uECC_vli_nativeToBytes(Lout + NUM_ECC_BYTES + 1, NUM_ECC_BYTES, L_tmp + NUM_ECC_WORDS); +#else mbedtls_ecp_group curve; mbedtls_mpi w1_bn; mbedtls_ecp_point Ltemp; @@ -1230,21 +1573,28 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_point_write_binary(&curve, &Ltemp, MBEDTLS_ECP_PF_UNCOMPRESSED, L_len, Uint8::to_uchar(Lout), *L_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); +#endif exit: _log_mbedTLS_error(result); +#if !defined(MBEDTLS_USE_TINYCRYPT) mbedtls_ecp_point_free(&Ltemp); mbedtls_mpi_free(&w1_bn); mbedtls_ecp_group_free(&curve); +#endif return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointIsValid(void * R) { +#if defined(MBEDTLS_USE_TINYCRYPT) + if (uECC_valid_point((const uECC_word_t *) R) != 0) +#else Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_check_pubkey(&context->curve, (mbedtls_ecp_point *) R) != 0) +#endif { return CHIP_ERROR_INTERNAL; } @@ -1288,7 +1638,7 @@ CHIP_ERROR ValidateCertificateChain(const uint8_t * rootCertificate, size_t root VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kRootFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Verify the chain against the root */ - mbedResult = mbedtls_x509_crt_verify(&certChain, &rootCert, nullptr, nullptr, &flags, nullptr, nullptr); + mbedResult = mbedtls_x509_crt_verify(&certChain, &rootCert, NULL, NULL, &flags, NULL, NULL); switch (mbedResult) { diff --git a/src/crypto/hsm/CHIPCryptoPALHsm.h b/src/crypto/hsm/CHIPCryptoPALHsm.h index c981a56062b247..185830ca744375 100644 --- a/src/crypto/hsm/CHIPCryptoPALHsm.h +++ b/src/crypto/hsm/CHIPCryptoPALHsm.h @@ -116,7 +116,7 @@ class P256PublicKeyHSM : public P256PublicKey class P256KeypairHSM : public P256Keypair { public: - P256KeypairHSM() + P256KeypairHSM() : P256Keypair() { provisioned_key = false; keyid = 0; @@ -126,6 +126,8 @@ class P256KeypairHSM : public P256Keypair virtual CHIP_ERROR Initialize() override; + virtual CHIP_ERROR Initialize(P256PlaintextKeypair & input) override; + virtual CHIP_ERROR Serialize(P256SerializedKeypair & output) const override; virtual CHIP_ERROR Deserialize(P256SerializedKeypair & input) override; diff --git a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp index 1007ba2c395973..61da170cd8a4ac 100644 --- a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp +++ b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp @@ -121,6 +121,14 @@ CHIP_ERROR P256KeypairHSM::Initialize() return CHIP_NO_ERROR; } +CHIP_ERROR P256Keypair::Initialize(P256PlaintextKeypair & input) +{ + // TODO: Support initialising a key from plaintext bytes when running + // FabricTable / CASE unit tests with plaintext keys on a device with + // this implementation + return CHIP_ERROR_NOT_IMPLEMENTED; +} + CHIP_ERROR P256KeypairHSM::ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P256ECDSASignature & out_signature) const { CHIP_ERROR error = CHIP_ERROR_INTERNAL; diff --git a/src/darwin/Framework/CHIP/MTRP256KeypairBridge.h b/src/darwin/Framework/CHIP/MTRP256KeypairBridge.h index 29cbeed4ac7dfe..bf36f137c36b57 100644 --- a/src/darwin/Framework/CHIP/MTRP256KeypairBridge.h +++ b/src/darwin/Framework/CHIP/MTRP256KeypairBridge.h @@ -33,6 +33,8 @@ class MTRP256KeypairBridge : public chip::Crypto::P256Keypair CHIP_ERROR Initialize() override; + CHIP_ERROR Initialize(chip::Crypto::P256PlaintextKeypair & input) override; + CHIP_ERROR Serialize(chip::Crypto::P256SerializedKeypair & output) const override; CHIP_ERROR Deserialize(chip::Crypto::P256SerializedKeypair & input) override; diff --git a/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm b/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm index a48c2bccc736f7..fcb39c7faa095e 100644 --- a/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm +++ b/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm @@ -49,6 +49,14 @@ return CHIP_NO_ERROR; } +CHIP_ERROR MTRP256KeypairBridge::Initialize(P256PlaintextKeypair & input) +{ + // Todo: support initialising a key from plaintext bytes when running + // FabricTable / CASE unit tests with plaintext keys on a device with + // this implementation + return CHIP_ERROR_NOT_IMPLEMENTED; +} + CHIP_ERROR MTRP256KeypairBridge::Serialize(P256SerializedKeypair & output) const { if (!HasKeypair()) { diff --git a/src/platform/EFR32/efr32-chip-mbedtls-config.h b/src/platform/EFR32/efr32-chip-mbedtls-config.h index edddb2abb6f0c8..dcb1839e1db3a4 100644 --- a/src/platform/EFR32/efr32-chip-mbedtls-config.h +++ b/src/platform/EFR32/efr32-chip-mbedtls-config.h @@ -80,7 +80,6 @@ #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_PK_WRITE_C -#define MBEDTLS_PKCS5_C #define MBEDTLS_PLATFORM_C #define MBEDTLS_PLATFORM_MEMORY #define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS @@ -101,6 +100,7 @@ #define MBEDTLS_SSL_PROTO_DTLS #define MBEDTLS_SSL_SRV_C #define MBEDTLS_SSL_TLS_C +#define MBEDTLS_USE_PSA_CRYPTO #define MBEDTLS_X509_CREATE_C #define MBEDTLS_X509_CSR_WRITE_C #define MBEDTLS_X509_CRL_PARSE_C diff --git a/src/platform/ESP32/ESP32FactoryDataProvider.cpp b/src/platform/ESP32/ESP32FactoryDataProvider.cpp index 443374b2c4421b..29ba00ea772d5a 100644 --- a/src/platform/ESP32/ESP32FactoryDataProvider.cpp +++ b/src/platform/ESP32/ESP32FactoryDataProvider.cpp @@ -32,11 +32,11 @@ static constexpr uint32_t kDACPublicKeySize = 65; CHIP_ERROR LoadKeypairFromRaw(ByteSpan privateKey, ByteSpan publicKey, Crypto::P256Keypair & keypair) { - Crypto::P256SerializedKeypair serializedKeypair; - ReturnErrorOnFailure(serializedKeypair.SetLength(privateKey.size() + publicKey.size())); - memcpy(serializedKeypair.Bytes(), publicKey.data(), publicKey.size()); - memcpy(serializedKeypair.Bytes() + publicKey.size(), privateKey.data(), privateKey.size()); - return keypair.Deserialize(serializedKeypair); + Crypto::P256PlaintextKeypair plaintextKeypair; + ReturnErrorOnFailure(plaintextKeypair.SetLength(privateKey.size() + publicKey.size())); + memcpy(plaintextKeypair.Bytes(), publicKey.data(), publicKey.size()); + memcpy(plaintextKeypair.Bytes() + publicKey.size(), privateKey.data(), privateKey.size()); + return keypair.Initialize(plaintextKeypair); } } // namespace diff --git a/src/platform/android/CHIPP256KeypairBridge.cpp b/src/platform/android/CHIPP256KeypairBridge.cpp index f0029fd183d0e0..3be5587780c9d3 100644 --- a/src/platform/android/CHIPP256KeypairBridge.cpp +++ b/src/platform/android/CHIPP256KeypairBridge.cpp @@ -76,6 +76,14 @@ CHIP_ERROR CHIPP256KeypairBridge::Initialize() return CHIP_NO_ERROR; } +CHIP_ERROR CHIPP256KeypairBridge::Initialize(P256PlaintextKeypair & input) +{ + // Todo: support initialising a key from plaintext bytes when running + // FabricTable / CASE unit tests with plaintext keys on a device with + // this implementation + return CHIP_ERROR_NOT_IMPLEMENTED; +} + CHIP_ERROR CHIPP256KeypairBridge::Serialize(P256SerializedKeypair & output) const { if (!HasKeypair()) diff --git a/src/platform/android/CHIPP256KeypairBridge.h b/src/platform/android/CHIPP256KeypairBridge.h index 3cb4dd217fa8e5..860c9294a07585 100644 --- a/src/platform/android/CHIPP256KeypairBridge.h +++ b/src/platform/android/CHIPP256KeypairBridge.h @@ -46,6 +46,8 @@ class CHIPP256KeypairBridge : public chip::Crypto::P256Keypair CHIP_ERROR Initialize() override; + CHIP_ERROR Initialize(chip::Crypto::P256PlaintextKeypair & input) override; + CHIP_ERROR Serialize(chip::Crypto::P256SerializedKeypair & output) const override; CHIP_ERROR Deserialize(chip::Crypto::P256SerializedKeypair & input) override; diff --git a/src/platform/nrfconnect/FactoryDataProvider.cpp b/src/platform/nrfconnect/FactoryDataProvider.cpp index 9800bea2b34ebb..f348e9c9c84bda 100644 --- a/src/platform/nrfconnect/FactoryDataProvider.cpp +++ b/src/platform/nrfconnect/FactoryDataProvider.cpp @@ -35,7 +35,7 @@ CHIP_ERROR LoadKeypairFromRaw(ByteSpan privateKey, ByteSpan publicKey, Crypto::P ReturnErrorOnFailure(serializedKeypair.SetLength(privateKey.size() + publicKey.size())); memcpy(serializedKeypair.Bytes(), publicKey.data(), publicKey.size()); memcpy(serializedKeypair.Bytes() + publicKey.size(), privateKey.data(), privateKey.size()); - return keypair.Deserialize(serializedKeypair); + return keypair.Initialize(serializedKeypair); } } // namespace diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 9c62a48e046908..70ed73600e967c 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -232,19 +232,19 @@ CHIP_ERROR InitCredentialSets() FabricInfo commissionerFabric; { - P256SerializedKeypair opKeysSerialized; + P256PlaintextKeypair opKeys; // TODO: Rename gCommissioner* to gInitiator* - memcpy((uint8_t *) (opKeysSerialized), sTestCert_Node01_02_PublicKey, sTestCert_Node01_02_PublicKey_Len); - memcpy((uint8_t *) (opKeysSerialized) + sTestCert_Node01_02_PublicKey_Len, sTestCert_Node01_02_PrivateKey, + memcpy((uint8_t *) (opKeys), sTestCert_Node01_02_PublicKey, sTestCert_Node01_02_PublicKey_Len); + memcpy((uint8_t *) (opKeys) + sTestCert_Node01_02_PublicKey_Len, sTestCert_Node01_02_PrivateKey, sTestCert_Node01_02_PrivateKey_Len); - ReturnErrorOnFailure(opKeysSerialized.SetLength(sTestCert_Node01_02_PublicKey_Len + sTestCert_Node01_02_PrivateKey_Len)); + ReturnErrorOnFailure(opKeys.SetLength(sTestCert_Node01_02_PublicKey_Len + sTestCert_Node01_02_PrivateKey_Len)); chip::ByteSpan rcacSpan(sTestCert_Root01_Chip, sTestCert_Root01_Chip_Len); chip::ByteSpan icacSpan(sTestCert_ICA01_Chip, sTestCert_ICA01_Chip_Len); chip::ByteSpan nocSpan(sTestCert_Node01_02_Chip, sTestCert_Node01_02_Chip_Len); - chip::ByteSpan opKeySpan(opKeysSerialized.ConstBytes(), opKeysSerialized.Length()); + chip::ByteSpan opKeySpan(opKeys.ConstBytes(), opKeys.Length()); ReturnErrorOnFailure( gCommissionerFabrics.AddNewFabricForTest(rcacSpan, icacSpan, nocSpan, opKeySpan, &gCommissionerFabricIndex)); @@ -260,16 +260,16 @@ CHIP_ERROR InitCredentialSets() FabricInfo deviceFabric; { - P256SerializedKeypair opKeysSerialized; + P256PlaintextKeypair opKeys; auto deviceOpKey = Platform::MakeUnique(); - memcpy((uint8_t *) (opKeysSerialized), sTestCert_Node01_01_PublicKey, sTestCert_Node01_01_PublicKey_Len); - memcpy((uint8_t *) (opKeysSerialized) + sTestCert_Node01_01_PublicKey_Len, sTestCert_Node01_01_PrivateKey, + memcpy((uint8_t *) (opKeys), sTestCert_Node01_01_PublicKey, sTestCert_Node01_01_PublicKey_Len); + memcpy((uint8_t *) (opKeys) + sTestCert_Node01_01_PublicKey_Len, sTestCert_Node01_01_PrivateKey, sTestCert_Node01_01_PrivateKey_Len); - ReturnErrorOnFailure(opKeysSerialized.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len)); + ReturnErrorOnFailure(opKeys.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len)); - ReturnErrorOnFailure(deviceOpKey->Deserialize(opKeysSerialized)); + ReturnErrorOnFailure(deviceOpKey->Initialize(opKeys)); // Use an injected operational key for device gDeviceOperationalKeystore.Init(1, std::move(deviceOpKey)); diff --git a/src/tools/chip-cert/Cmd_GenCD.cpp b/src/tools/chip-cert/Cmd_GenCD.cpp index 4d4b30212a35a1..f530773993cb0f 100644 --- a/src/tools/chip-cert/Cmd_GenCD.cpp +++ b/src/tools/chip-cert/Cmd_GenCD.cpp @@ -1156,9 +1156,9 @@ bool Cmd_GenCD(int argc, char * argv[]) // Initialize P256Keypair from EVP_PKEY. P256Keypair keypair; { - P256SerializedKeypair serializedKeypair; - VerifyOrReturnError(SerializeKeyPair(key.get(), serializedKeypair), false); - VerifyOrReturnError(keypair.Deserialize(serializedKeypair) == CHIP_NO_ERROR, false); + P256PlaintextKeypair plaintextKeypair; + VerifyOrReturnError(ExportKeyPair(key.get(), plaintextKeypair), false); + VerifyOrReturnError(keypair.Initialize(plaintextKeypair) == CHIP_NO_ERROR, false); } // Encode CD TLV content. diff --git a/src/tools/chip-cert/KeyUtils.cpp b/src/tools/chip-cert/KeyUtils.cpp index 6ab9290663f899..05d210ab181ced 100644 --- a/src/tools/chip-cert/KeyUtils.cpp +++ b/src/tools/chip-cert/KeyUtils.cpp @@ -42,7 +42,7 @@ namespace { KeyFormat DetectKeyFormat(const uint8_t * key, uint32_t keyLen) { - static uint32_t p256SerializedKeypairLen = kP256_PublicKey_Length + kP256_PrivateKey_Length; + static uint32_t p256PlaintextKeypairLen = kP256_PublicKey_Length + kP256_PrivateKey_Length; static const uint8_t chipRawPrefix[] = { 0x04 }; static const char * chipHexPrefix = "04"; static const char * chipB64Prefix = "B"; @@ -54,15 +54,15 @@ KeyFormat DetectKeyFormat(const uint8_t * key, uint32_t keyLen) VerifyOrReturnError(key != nullptr, kKeyFormat_Unknown); - if ((keyLen == p256SerializedKeypairLen) && (memcmp(key, chipRawPrefix, sizeof(chipRawPrefix)) == 0)) + if ((keyLen == p256PlaintextKeypairLen) && (memcmp(key, chipRawPrefix, sizeof(chipRawPrefix)) == 0)) { return kKeyFormat_Chip_Raw; } - if ((keyLen == HEX_ENCODED_LENGTH(p256SerializedKeypairLen)) && (memcmp(key, chipHexPrefix, strlen(chipHexPrefix)) == 0)) + if ((keyLen == HEX_ENCODED_LENGTH(p256PlaintextKeypairLen)) && (memcmp(key, chipHexPrefix, strlen(chipHexPrefix)) == 0)) { return kKeyFormat_Chip_Hex; } - if ((keyLen == BASE64_ENCODED_LEN(p256SerializedKeypairLen)) && (memcmp(key, chipB64Prefix, strlen(chipB64Prefix)) == 0)) + if ((keyLen == BASE64_ENCODED_LEN(p256PlaintextKeypairLen)) && (memcmp(key, chipB64Prefix, strlen(chipB64Prefix)) == 0)) { return kKeyFormat_Chip_Base64; } @@ -160,7 +160,7 @@ bool DeserializeKeyPair(const uint8_t * keyPair, uint32_t keyPairLen, EVP_PKEY * } // namespace -bool SerializeKeyPair(EVP_PKEY * key, P256SerializedKeypair & serializedKeypair) +bool SerializeKeyPair(EVP_PKEY * key, P256PlaintextKeypair & serializedKeypair) { const EC_KEY * ecKey = nullptr; const BIGNUM * privKeyBN = nullptr; @@ -394,7 +394,7 @@ bool WriteKey(const char * fileName, EVP_PKEY * key, KeyFormat keyFmt) dataFormat = kDataFormat_Hex; { - P256SerializedKeypair serializedKeypair; + P256PlaintextKeypair serializedKeypair; VerifyOrExit(SerializeKeyPair(key, serializedKeypair), res = false); VerifyOrExit(WriteDataIntoFile(fileName, serializedKeypair.Bytes(), serializedKeypair.Length(), dataFormat), res = false); From bb6df593ad677b2bd584fdcd0da8d5efeb305b96 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Mon, 25 Jul 2022 17:59:10 +0000 Subject: [PATCH 2/2] Restyled by clang-format --- src/credentials/tests/TestFabricTable.cpp | 4 ++-- src/crypto/CHIPCryptoPAL.h | 4 ++-- src/tools/chip-cert/KeyUtils.cpp | 18 +++++++++--------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/credentials/tests/TestFabricTable.cpp b/src/credentials/tests/TestFabricTable.cpp index 36fda8c86a82f0..0fbca9059fa8c4 100644 --- a/src/credentials/tests/TestFabricTable.cpp +++ b/src/credentials/tests/TestFabricTable.cpp @@ -134,8 +134,8 @@ static CHIP_ERROR LoadTestFabric_Node02_01(nlTestSuite * inSuite, FabricTable & ByteSpan nocSpan(TestCerts::sTestCert_Node02_01_Chip, TestCerts::sTestCert_Node02_01_Chip_Len); NL_TEST_ASSERT(inSuite, - opKeys.SetLength(TestCerts::sTestCert_Node02_01_PublicKey_Len + - TestCerts::sTestCert_Node02_01_PrivateKey_Len) == CHIP_NO_ERROR); + opKeys.SetLength(TestCerts::sTestCert_Node02_01_PublicKey_Len + TestCerts::sTestCert_Node02_01_PrivateKey_Len) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, gFabric2OpKey.Initialize(opKeys) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, fabricTable.AddNewPendingTrustedRootCert(rcacSpan) == CHIP_NO_ERROR); diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index 11b103583ac597..08213ccee024ba 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -73,8 +73,8 @@ constexpr size_t kSpake2p_Max_PBKDF_Salt_Length = 32; constexpr uint32_t kSpake2p_Min_PBKDF_Iterations = 1000; constexpr uint32_t kSpake2p_Max_PBKDF_Iterations = 100000; -constexpr size_t kP256_PrivateKey_Length = CHIP_CRYPTO_GROUP_SIZE_BYTES; -constexpr size_t kP256_PublicKey_Length = CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES; +constexpr size_t kP256_PrivateKey_Length = CHIP_CRYPTO_GROUP_SIZE_BYTES; +constexpr size_t kP256_PublicKey_Length = CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES; constexpr size_t kMax_SerializeKey_Length = kP256_PublicKey_Length + kP256_PrivateKey_Length; constexpr size_t kMax_PlaintextKey_Length = kP256_PublicKey_Length + kP256_PrivateKey_Length; diff --git a/src/tools/chip-cert/KeyUtils.cpp b/src/tools/chip-cert/KeyUtils.cpp index 05d210ab181ced..a86794d1da7ed6 100644 --- a/src/tools/chip-cert/KeyUtils.cpp +++ b/src/tools/chip-cert/KeyUtils.cpp @@ -42,15 +42,15 @@ namespace { KeyFormat DetectKeyFormat(const uint8_t * key, uint32_t keyLen) { - static uint32_t p256PlaintextKeypairLen = kP256_PublicKey_Length + kP256_PrivateKey_Length; - static const uint8_t chipRawPrefix[] = { 0x04 }; - static const char * chipHexPrefix = "04"; - static const char * chipB64Prefix = "B"; - static const uint8_t derRawPrefix[] = { 0x30, 0x77, 0x02, 0x01, 0x01, 0x04 }; - static const char * derHexPrefix = "307702010104"; - static const char * ecPEMMarker = "-----BEGIN EC PRIVATE KEY-----"; - static const char * pkcs8PEMMarker = "-----BEGIN PRIVATE KEY-----"; - static const char * ecPUBPEMMarker = "-----BEGIN PUBLIC KEY-----"; + static uint32_t p256PlaintextKeypairLen = kP256_PublicKey_Length + kP256_PrivateKey_Length; + static const uint8_t chipRawPrefix[] = { 0x04 }; + static const char * chipHexPrefix = "04"; + static const char * chipB64Prefix = "B"; + static const uint8_t derRawPrefix[] = { 0x30, 0x77, 0x02, 0x01, 0x01, 0x04 }; + static const char * derHexPrefix = "307702010104"; + static const char * ecPEMMarker = "-----BEGIN EC PRIVATE KEY-----"; + static const char * pkcs8PEMMarker = "-----BEGIN PRIVATE KEY-----"; + static const char * ecPUBPEMMarker = "-----BEGIN PUBLIC KEY-----"; VerifyOrReturnError(key != nullptr, kKeyFormat_Unknown);