From 99f1620e7d356bc265971574dcb623f288e01cdb Mon Sep 17 00:00:00 2001 From: Pol Henarejos Date: Sat, 18 Mar 2023 18:40:27 +0100 Subject: [PATCH] Fixes #22. SC-HSM returns the result with a 0x04 prepended. This comes from OpenSC but it is not clear the exact reason. 0x04 is usually for encoding uncompressed EC points but in that case it does not seem to make sense. Signed-off-by: Pol Henarejos --- src/hsm/cmd_decrypt_asym.c | 9 ++++++--- tests/conftest.py | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/hsm/cmd_decrypt_asym.c b/src/hsm/cmd_decrypt_asym.c index 893dcc3..bee94dd 100644 --- a/src/hsm/cmd_decrypt_asym.c +++ b/src/hsm/cmd_decrypt_asym.c @@ -129,15 +129,18 @@ int cmd_decrypt_asym() { return SW_DATA_INVALID(); } size_t olen = 0; + // The SmartCard-HSM returns the point result of the DH operation + // with a leading '04' + res_APDU[0] = 0x04; r = - mbedtls_ecdh_calc_secret(&ctx, &olen, res_APDU, MBEDTLS_ECP_MAX_BYTES, random_gen, + mbedtls_ecdh_calc_secret(&ctx, &olen, res_APDU + 1, MBEDTLS_ECP_MAX_BYTES, random_gen, NULL); mbedtls_ecdh_free(&ctx); if (r != 0) { return SW_EXEC_ERROR(); } if (p2 == ALGO_EC_DH) { - res_APDU_size = olen; + res_APDU_size = olen + 1; } else { res_APDU_size = 0; @@ -175,7 +178,7 @@ int cmd_decrypt_asym() { if (file_get_size(tf) == kdom_uid_len && memcmp(file_get_data(tf), kdom_uid, kdom_uid_len) == 0) { file_new(EF_DKEK + n); - if (store_dkek_key(n, res_APDU) != CCID_OK) { + if (store_dkek_key(n, res_APDU + 1) != CCID_OK) { return SW_EXEC_ERROR(); } mbedtls_platform_zeroize(res_APDU, 32); diff --git a/tests/conftest.py b/tests/conftest.py index 4564729..5c9b718 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -411,7 +411,7 @@ class Device: def exchange(self, keyid, pubkey): resp = self.send(cla=0x80, command=0x62, p1=keyid, p2=Algorithm.ALGO_EC_ECDH.value, data=pubkey.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)) - return resp + return resp[1:] def parse_cvc(self, data): car = CVC().decode(data).car()