Search code examples
cgmp

mpz_set_srt Sets 0 to mpz_t


void decrypt_cert(mpz_t decrypted_cert, cert_message *cert, mpz_t key_exp, mpz_t key_mod) {
    mpz_t certificate;
    mpz_init(certificate);
    puts(cert->cert); // Prints Hex values i.e 0x98A6C
    mpz_set_str(certificate, cert->cert, HEX_BASE);
    puts(mpz_get_str(NULL,16,certificate)); // Prints 0
    perform_rsa(decrypted_cert, certificate, key_exp, key_mod);
}

In my method above. Line number 1 puts(cert->cert); Prints correct values of cert->cert but when I set certificate with this value and convert certificate back to string puts(mpz_get_str(NULL,16,certificate)); prints out 0.

Any clue what is wrong with my code?


Solution

  •  mpz_set_str(certificate, cert->cert, HEX_BASE);
    

    is not going to be able to parse your string if it starts with 0x.

    You either have to:

    • Pass 0 as the base, in which case mpz_set_str will parse the string as hex if it starts with 0x
    • Pass in the base as 16 and skip past the 0x. i.e. call mpz_set_str(certificate, &cert->cert[2], HEX_BASE);

    Below is a small sample program you can use for testing by passing in e.g. "0x1234" vs "1234"

    #include <gmp.h>
    #include <stdio.h>
    int  main(int argc, char *argv[])
    {
        int rc;
        mpz_t certificate; 
        mpz_init(certificate);
        rc = mpz_set_str(certificate, "1234", 16);
        printf("mpz_set_str returned %d\n", rc);
        puts(mpz_get_str(NULL,16,certificate)); 
        return 0;
    
    }