From ff641f7cdcaf4e1ea805c7924121c6fe970641b2 Mon Sep 17 00:00:00 2001 From: Stefan Berger Date: Fri, 4 May 2018 16:53:19 -0400 Subject: [PATCH] swtpm_cert: simplify two's completement implementation Simplify the two's complement implementation by converting the number into a big endian and writing it out into a byte array that is prefixed with a 0-byte. This covers all unsigned ints while the previous imple- mentation would have been wrong once the number exceeded 255. Signed-off-by: Stefan Berger --- src/swtpm_cert/ek-cert.c | 30 ++++++++---------------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/src/swtpm_cert/ek-cert.c b/src/swtpm_cert/ek-cert.c index 3ff26a1..b31f717 100644 --- a/src/swtpm_cert/ek-cert.c +++ b/src/swtpm_cert/ek-cert.c @@ -186,22 +186,6 @@ hex_str_to_bin(const char *hexstr, int *modulus_len) return result; } -static size_t -calc_twos_complement(unsigned int number, - unsigned char *twoscomp, size_t twoscomp_len) -{ - size_t i = 0; - - twoscomp[i++] = 0; - - do { - twoscomp[i++] = (number & 0xff); - number >>= 8; - } while (number && i < twoscomp_len); - - return i; -} - static gnutls_pubkey_t create_rsa_from_modulus(unsigned char *modulus, unsigned int modulus_len, uint32_t exponent) @@ -493,8 +477,8 @@ create_tpm_specification_info(const char *spec_family, { ASN1_TYPE at = ASN1_TYPE_EMPTY; int err; - unsigned char twoscomp[5]; - size_t twoscomp_len; + unsigned int bigendian; + unsigned char twoscomp[1 + sizeof(bigendian)] = { 0, }; err = asn_init(); if (err != ASN1_SUCCESS) { @@ -521,21 +505,23 @@ create_tpm_specification_info(const char *spec_family, goto cleanup; } - twoscomp_len = calc_twos_complement(spec_level, twoscomp, sizeof(twoscomp)); + bigendian = htobe32(spec_level); + memcpy(&twoscomp[1], &bigendian, sizeof(bigendian)); err = asn1_write_value(at, "tpmSpecificationSeq.tpmSpecificationSet.tpmSpecification.level", - twoscomp, twoscomp_len); + twoscomp, sizeof(twoscomp)); if (err != ASN1_SUCCESS) { fprintf(stderr, "c1d. asn1_write_value error: %d\n", err); goto cleanup; } - twoscomp_len = calc_twos_complement(spec_revision, twoscomp, sizeof(twoscomp)); + bigendian = htobe32(spec_revision); + memcpy(&twoscomp[1], &bigendian, sizeof(bigendian)); err = asn1_write_value(at, "tpmSpecificationSeq.tpmSpecificationSet.tpmSpecification.revision", - twoscomp, twoscomp_len); + twoscomp, sizeof(twoscomp)); if (err != ASN1_SUCCESS) { fprintf(stderr, "c1e. asn1_write_value error: %d\n", err); goto cleanup;