What does ‘% 02x’ do exactly?

Posted on

Question :

I was seeing some examples of hash functions > from OpenSSL and I came across the format specifier / a> %02x . I do not know very well their purpose we codes that I saw. I even understand that %02x is to fill the field with zeros and 2 is the number of zeros that will have in that fill (I think that).

Well, here’s a code developed by me where I had to use (I do not know why I had to use it) %02x :

#include <stdio.h>
#include <string.h>
#include <string.h>
#include <openssl/sha.h>

void get_string(char *string, size_t max_input_size){

    fgets(string, max_input_size, stdin);

    unsigned int len=strlen(string);

    string[len-1]='
Write >FN P90

Digest: 45603ce52cd32a33e3e60c219d0c18e6bd32af24ac39aa000d84e763d23c3031

';
}

int main(void){

char string[50];
unsigned char digest[SHA256_DIGEST_LENGTH];

printf("Write >");
get_string(string, 50);

SHA256((unsigned char*)string, strlen(string), digest);

char stringMD[SHA256_DIGEST_LENGTH*2+1];

for(unsigned int i=0; i<SHA256_DIGEST_LENGTH; i++){

sprintf(&stringMD[i*2], "%02x", (unsigned int)digest[i]);
}

printf("nnDigest: %snn", stringMD);

return 0;
}

Execution (with %02x ):

Write >FN P90

Digest: 45603ce52cd32a33e3e6c

Execution (with only %x ):

#include <stdio.h>
#include <string.h>
#include <string.h>
#include <openssl/sha.h>

void get_string(char *string, size_t max_input_size){

    fgets(string, max_input_size, stdin);

    unsigned int len=strlen(string);

    string[len-1]='
Write >FN P90

Digest: 45603ce52cd32a33e3e60c219d0c18e6bd32af24ac39aa000d84e763d23c3031

';
}

int main(void){

char string[50];
unsigned char digest[SHA256_DIGEST_LENGTH];

printf("Write >");
get_string(string, 50);

SHA256((unsigned char*)string, strlen(string), digest);

char stringMD[SHA256_DIGEST_LENGTH*2+1];

for(unsigned int i=0; i<SHA256_DIGEST_LENGTH; i++){

sprintf(&stringMD[i*2], "%02x", (unsigned int)digest[i]);
}

printf("nnDigest: %snn", stringMD);

return 0;
}

However, what is the purpose of %02x ?

    

Answer :

According to documentation displays the whole number as hexadecimal ensuring that it always has 2 digits, 0 to the left if you have only 1 or 0 digits. Generally it is the only way to generate hexadecimal correctly, especially in cases where it is only part of a larger number.

    

You have a string called stringMD , which may have garbage at the beginning of the program.

If you do not all fill your positions with something, there may be 02 characters in a certain region.

As you are filling in two by two (see below),

sprintf(/* destaque ao i*2 >>>>*/ &stringMD[i*2], "%02x", ...

If you forget about %code% of the format, the fill may be partial.

    

Leave a Reply

Your email address will not be published. Required fields are marked *