ctypeslibgcrypt

C and libgcrypt. Str to type gcry_error_t. Then add


I am trying to convert a number in a string "255" to type gcry_mpi_t. gcry_mpi_dump show me 323535 and than gcry_mpi_add and gcry_mpi_print(GCRYMPI_FMT_USG... ) doesn't work normal.

#include <gcrypt.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>


const char *byte_to_binary(int x)   
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1) {
        strcat(b, ((x & z) == z) ? "1" : "0");
    }

    return b;
}





int main() {

gcry_mpi_t max_ul = gcry_mpi_new(64);         
gcry_mpi_t mul = gcry_mpi_new(128);                    
gcry_mpi_t cript_prime;

char mybignum[5] = {0}; 

cript_prime = gcry_mpi_new(5);

mybignum[0] ='2';
mybignum[1] ='5';
mybignum[2]='5';


printf("First %s\n", mybignum);


char buffer[60] = {0}; 

size_t scanned = 0; 

strcpy(mybignum, "255"); 
gcry_mpi_scan(&max_ul, GCRYMPI_FMT_USG, &mybignum, 5, NULL);

printf("read : %ld \n", scanned);


printf(" max_ul is  ");

gcry_mpi_dump(max_ul); printf("\n");

gcry_mpi_add(mul,max_ul,max_ul );

printf(" mul is ");
// выводим на экран
gcry_mpi_dump(mul); printf("\n");



gcry_mpi_print(GCRYMPI_FMT_USG, buffer, 30 ,  &scanned, mul);

printf("\nwrite : %ld \n", scanned);

printf("\n output the line %s \n", buffer);

for (int i=0; i<10  ; i++)
{
    printf("%s\n",byte_to_binary(buffer[i]) );
}


printf(" \n mul is: ");



gcry_mpi_dump(mul); printf("\n");





gcry_mpi_release(mul);
gcry_mpi_release(max_ul);
printf("____________________________________\n");


 return 0 ; 
}

You can see output:

output

lib was taken from https://gnupg.org/download/index.html

gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)

Compiling with command. gcc test.c -lgcrypt

If you have examples of this type, i would like to see.


Solution

  • The documentation of gcry_mpi_scan() says:

    Convert the external representation of an integer stored in buffer
    format describes the format of the MPI as stored in buffer: …
    GCRYMPI_FMT_USG Simple unsigned integer.

    This is indeed somewhat unclear, hence you misinterpreted external representation as being an ASCII decimal representation; in fact it means the integer representation as stored in memory. So, to store the number 255 in char mybignum[5] and convert it, you can write:

    *mybignum = 255;
    gcry_error_t error = gcry_mpi_scan(&max_ul, GCRYMPI_FMT_USG, mybignum, 1, &scanned);
    

    Accordingly, the gcry_mpi_print(GCRYMPI_FMT_USG, buffer, 30 , &scanned, mul) converts the MPI a into a representation which is not suitable for printing with printf("\n output the line %s \n", buffer).