1

I have a given simple code snippet that is supposed to generate a 128-bit encryption key. How do I print out the values to the console? Here's the code:

#include <stdio.h>
#include <stdlib.h>

#define LEN 16 // 128 bits

void main()
{
    unsigned char *key = (unsigned char *) malloc(sizeof(unsigned char)*LEN);
    FILE* random = fopen("/dev/urandom", "r");
    fread(key, sizeof(unsigned char)*LEN, 1, random);
    fclose(random);
}

To be more specific: the instructions say: "Print out the numbers."

C0DeX
  • 147
  • 2
  • 11

2 Answers2

0

Generating human readable binary data will usually involve hex or base64. Assuming hex code is acceptable:

for (int i=0 ; i<LEN ; i++ ) {
   printf("%02x", key[i]) ;
} ;
printf("\n") ;
dash-o
  • 13,723
  • 1
  • 10
  • 37
0

The most usual method of "human readable" presentation of binary data is to use hexadecimal, where each digit represents 4 bits.

for( int b = 0; b < len; b++ ) 
{
    printf( "%2.2X ", (int)key[b] ) ;
}
Clifford
  • 88,407
  • 13
  • 85
  • 165