From 8b292687f5dd9f21df4e1ee56b6845c8e40ac362 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 29 Nov 2023 13:13:10 -0800 Subject: [PATCH] Fixes for ECC sign where the r/s is does not match key size and needs zero padded. --- tools/keytools/sign.c | 22 +++++++++++++++------- tools/tpm/policy_sign.c | 11 ++++++++--- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/tools/keytools/sign.c b/tools/keytools/sign.c index 1cb00b65c..f88412d9f 100644 --- a/tools/keytools/sign.c +++ b/tools/keytools/sign.c @@ -864,18 +864,26 @@ static int sign_digest(int sign, int hash_algo, sign == SIGN_ECC521) { mp_int r, s; - int sigSz; - if (sign == SIGN_ECC256) sigSz = 32; - if (sign == SIGN_ECC384) sigSz = 48; - if (sign == SIGN_ECC521) sigSz = 66; + int keySz; + if (sign == SIGN_ECC256) keySz = 32; + if (sign == SIGN_ECC384) keySz = 48; + if (sign == SIGN_ECC521) keySz = 66; + + *signature_sz = keySz*2; + memset(signature, 0, *signature_sz); mp_init(&r); mp_init(&s); ret = wc_ecc_sign_hash_ex(digest, digest_sz, &rng, &key.ecc, &r, &s); - mp_to_unsigned_bin(&r, &signature[0]); - mp_to_unsigned_bin(&s, &signature[sigSz]); + if (ret == 0) { + word32 rSz, sSz; + /* export sign r/s - zero pad to key size */ + rSz = mp_unsigned_bin_size(&r); + mp_to_unsigned_bin(&r, &signature[keySz - rSz]); + sSz = mp_unsigned_bin_size(&s); + mp_to_unsigned_bin(&s, &signature[keySz + (keySz - sSz)]); + } mp_clear(&r); mp_clear(&s); - *signature_sz = sigSz*2; } else #endif diff --git a/tools/tpm/policy_sign.c b/tools/tpm/policy_sign.c index 2af3fe591..9cda2c4ff 100644 --- a/tools/tpm/policy_sign.c +++ b/tools/tpm/policy_sign.c @@ -140,11 +140,16 @@ static int PolicySign(int alg, const char* keyFile, byte* hash, word32 hashSz, rc = wc_ecc_sign_hash_ex(hash, hashSz, &rng, &key.ecc, &r, &s); } if (rc == 0) { - mp_to_unsigned_bin(&r, sig); - mp_to_unsigned_bin(&s, sig + keySz); + word32 rSz, sSz; + *sigSz = keySz * 2; + memset(sig, 0, *sigSz); + /* export sign r/s - zero pad to key size */ + rSz = mp_unsigned_bin_size(&r); + mp_to_unsigned_bin(&r, &sig[keySz - rSz]); + sSz = mp_unsigned_bin_size(&s); + mp_to_unsigned_bin(&s, &sig[keySz + (keySz - sSz)]); mp_clear(&r); mp_clear(&s); - *sigSz = keySz * 2; } } wc_ecc_free(&key.ecc);