In: Computer Science
A big problem of the blocking behavior of /dev/random is that blocking can lead to denial of service attacks. Therefore, it is recommended that we use /dev/urandom to get random numbers. To do that in our program, we just need to read directly from this device file. The following code snippet shows how:
#define LEN 16 // 128 bits
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);
Please modify the above code snippet to generate a 256-bit encryption key. Please compile and run your code; print out the numbers and include the screenshot in the report.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN 64
char hexa(int n) // Function to convert decimal to
hexadecimal
{
char array[16]
={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
return(array[n]);
}
int main()
{
unsigned char *key = ( unsigned char *) malloc(sizeof(unsigned
char)*LEN);
int a[LEN],i;
char en[LEN]="";
FILE* random = fopen("/dev/urandom","r"); // It returns random
characters
fread(key, sizeof(unsigned char)*LEN, 1, random); //Storing all the
characters in key (a character array)
fclose(random);
/*All the random characters have int value less then 256,
storing their corresponding integer values (mod 16) in integer
array*/
for(int i=0;i<LEN;i++)
{
a[i] = ((int)key[i])%16;
}
for(int i=0;i<LEN;i++)
{
en[i] = hexa(a[i]);
}
printf("Encryption key is:\n");
for(int i=0;i<LEN;i++)
{
printf("%c",en[i]);
}
printf("\n");
return 0;
}
Here we are creating 256 bit hexadecimal encryption (as in AES 256-bit key). Each hexadecimal digit require 4 bit for representation, hence total number of characters in key will be 64.
Screenshot: