Pseudo Random number generation in C using libsodium - c

I am trying to create a sequence of integers which is the same everytime as the generator is seeded however I am struggling to get it working. Right now the sequence is never the same.
#include "sodium.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main()
{
if (sodium_init() == -1)
{
return 1;
}
unsigned int myInts[128];
char seed[randombytes_SEEDBYTES] = "a seeeeeed";
printf("%s", seed);
randombytes_buf_deterministic(myInts, 128, seed);
for (int i = 0; i < 128; i++)
{
printf("\n(%u)", myInts[i]);
}
}

The problem is, that here
randombytes_buf_deterministic(myInts, 128, seed);
you generate 128 bytes of pseudorandom-data, but your buffer
unsigned int myInts[128];
is sizeof(int)*128 bytes big. So you have to generate enough data with
randombytes_buf_deterministic(myInts, sizeof(myInts), seed);
to fill the whole buffer with deterministic values. Then it should give the output you expect.

Related

Why isn't my code reading the correct integers from a file?

So after playing a little bit with Craig Estey's answer, I managed to get the following piece of code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char **argv){
char *filename = argv[1];
if(filename == NULL) {
printf("Please specify a filename.\n");
exit(1);
}
FILE *fi = fopen(filename,"r");
printf("Finding size...\n");
int size = 0;
while(fscanf(fi,"%*d") != -1) size++;
rewind(fi);
int numbers[size];
while(fscanf(fi,"%d",&numbers[size]) != 1);
fclose(fi);
printf("Size of array: %d\n\n", size);
int idx=0,idx2=1,idx3=1,idx4=1;
printf("Elements: \n");
while (idx < size){
printf("%d\n",numbers[idx]);
idx++;
}
int maximum = numbers[0];
while (idx2 < size){
if (numbers[idx2] > maximum){
maximum = numbers[idx2];
}
idx2++;
}
printf("\nMax: %d\n",maximum);
int minimum = numbers[0];
while (idx3 < size){
if (numbers[idx3] < minimum){
minimum = numbers[idx3];
}
idx3++;
}
printf("Min: %d\n",minimum);
int sum = numbers[0];
while (idx4 < size){
sum = sum + numbers[idx4];
idx4++;
}
printf("Total: %d\n",sum);
}
Problem is, now it executes without halting, but still doesn't provide the right answer. My 'abcd.txt' file contains the following numbers:
5564
4324
863
98743
However, my result after executing reader.c is:
./reader abcd.txt
Finding size...
Size of array: 4
Elements:
0
0
1384783917
32713
Max: 1384783917
Min: 0
Total: 1384816630
Why is that, now? I cannot find why is it different than in the answer below. If I execute the exact code in the answer, it does return the right answer. Thanks in advance.
This is prefaced by my top comments.
You can't do: printf(numbers[idx2]); (i.e. the first argument has to be a format string). So, do: printf("%d\n",numbers[idx2]);
Doing sizeof(numbers) / sizeof(int) does not give an accurate count of the number actually filled in. It gives the maximum which will have garbage values at the end.
Because, there were so many errors, I couldn't list them all. I had to completely refactor your code. Just compare it in detail to yours to see the difference. You'll learn much more and more quickly than trying to patch what you already have.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
long int
findSize(char *filename)
{
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("findSize: unable to open file '%s' -- %s\n",
filename,strerror(errno));
exit(1);
}
fseek(fp, 0L, SEEK_END);
long int res = ftell(fp);
fclose(fp);
return res;
}
int
main(int argc, char **argv)
{
char *filename = argv[1];
if (filename == NULL) {
printf("please specify a filename\n");
exit(1);
}
printf("findSize\n");
int numbers[findSize(filename)];
printf("scanf\n");
FILE *fi = fopen(filename,"r");
int size = 0;
while (1) {
if (fscanf(fi,"%d",&numbers[size]) != 1)
break;
printf("scanf: %d\n",numbers[size]);
++size;
}
fclose(fi);
printf("size: %d\n",size);
for (int idx2 = 0; idx2 < size; ++idx2)
printf("%d\n",numbers[idx2]);
int maximum = numbers[0];
for (int idx3 = 1; idx3 < size; ++idx3) {
if (numbers[idx3] > maximum)
maximum = numbers[idx3];
}
printf("Max: %d\n", maximum);
int minimum = numbers[0];
for (int idx4 = 1; idx4 < size; ++idx4) {
if (numbers[idx4] < minimum)
minimum = numbers[idx4];
}
printf("Min: %d\n", minimum);
int sum = 0;
for (int idx5 = 0; idx5 < size; ++idx5)
sum = sum + numbers[idx5];
printf("Total: %d\n", sum);
return 0;
}
UPDATE:
First of all, thanks a lot for your work. Looking at your code (I cannot call it anymore my code as it's completely different)
Yes, it was intended as a guide for you to write/rewrite your own code, which you've done.
I see that the findSize function is mostly irrelevant.
It is technically correct, but would allocate [much] more space than was needed.
I tried to put another fscanf instead of calling a findSize function, but I don't know how this function works exactly.
Good for you in figuring out this alternate sizing algorithm.
Let me see if I get it: If there is a third argument, it stores each read element into the third argument (which should be a variable). But if there is no third element, and you put an * in the second argument, it doesn't store the read elements anywhere. Am I right?
Believe it or not, I don't use fscanf too much as it can be slow, so I'm not familiar with some of the more esoteric options. I've tested your new sizing loop and it appears to work, so I think your analysis may be correct.
Also, we could simply introduce an extra scalar int variable and do:
int size = 0;
while (1) {
int val;
if (fscanf(fi,"%d",&val) != 1)
break;
++size;
}
However, you're actual second fscanf loop that is used to read in the numbers will not work:
while (fscanf(fi, "%d", &numbers[size]) != 1);
This puts all numbers in the same index, namely size, which is one beyond the end of the numbers array, so this is undefined behavior.
Also, the loop condition is reversed from what it should be, so only one number would be filled in.
To fix this, we need an additional index variable and need to change the sense of the while loop:
int idx0 = 0;
while (fscanf(fi, "%d", &numbers[idx0]) == 1)
++idx0;
After this change, the rest of your updated code [min/max/sum] works fine.
Some notes on style:
As you noticed, my original posted code was a bit different (e.g. replacing while loops with for loops).
But, one thing I didn't do was reuse the index variable. That is, there isn't a need to have separate ones for each loop. They could all be changed to a single idx variable.
Using different symbols isn't wrong, and can add to clarity. But, idx, idx1, idx2 aren't as descriptive as they could be.
If you'd like to keep separate variables, I'd suggest more descriptive names such as: inpidx, minidx, maxidx, and sumidx

c - cheak readable bytes

need little help form you guys
i just wanna to cheak if the byte is readable or not, i have search for sulution but not find
hope you will help me
i have this code i need if tag that cheak if byte is readable
#include <windows.h>
#include <iostream>
#include <cstdlib>
#include <stdio.h>
void main()
{
float ramsize;
char *ch;
unsigned int j=128,readbyte;
long i;
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
ramsize = statex.ullTotalPhys;
for(i=0;i<ramsize;i = i+1)
{
ch = (char*) i;
readbyte = *ch;
// if readbyte is readable
printf("you have readable byte in address: %x , that contain in Binary:",&readbyte);
for(i=0;i<8;i++)
{
if(readbyte&j)
printf("1");
else
printf("0");
j=j>>1;
}
putchar('\n');
// if readbyte is not readable
printf("Sorry: you cant read this byte: %x",&readbyte);
}
}
If a byte is not readable the OS will send a signal to your process. You need to catch that signal or your program will terminate.
Read up on signals in your course textbook.

SHA_256 functions corrupting memory space

I've been trying to use the SHA_256 functions in sha256.h on a FreeBSD 9.1 system but it seems to be corrupting memory space of my program causing all kinds of manic behavior. I wrote up a quick program to just to play with those functions and still am having problems.
In the example below, int i is changed when I call SHA256_Init(), as shown by the output from the printf() statements surrounding it.
This is what I get running the code.
$ ./miner "hello world"
i = 0
i = 32
0000000032 9010a9cf81ce2c28a642fd03ddf6da5790c65c30cd4a148c4257d3fe488bacc7
Why is this value changing to 32? Am I missing something? The code is below...
#include <sha256.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#define DIFFICULTY 0
int main(int argc, const char **argv) {
uint nonce, i, j;
SHA256_CTX ctx;
size_t arglen;
unsigned char digest[32];
char * data;
if(argc < 1) exit(1);
arglen = strlen(argv[1]);
data = malloc(arglen + 1);
char digestStr[65];
i = 0;
do {
nonce = i;
strncpy(data, argv[1], arglen + 1);
printf("i = %i\n", i);
SHA256_Init(&ctx);
printf("i = %i\n", i);
SHA256_Update(&ctx, data, arglen);
SHA256_Update(&ctx, (unsigned char *) &nonce, sizeof(nonce));
SHA256_Final(digest, &ctx);
SHA256_End(&ctx, digestStr);
printf("%010i\t%s\n", i, digestStr);
j = 0;
while(j < 32 && digest[j] == '\0') {
j++;
}
i++;
} while(j < DIFFICULTY);
free(data);
return 0;
}
I just had this exact same problem and solved it.
The issue is that your are including a different header in your code than the SHA2 library you linked into your application is using.
In my case the SHA256_CTX struct was a different size in the openSSL library. The openSSL library's struct was 8 bytes bigger than the struct length in the file.
The function SHA256_Init(&ctx) does a memset on the SHA256_CTX struct which then corrupts 8 extra random bytes after the struct. I say random because it will do different things in a release vs debug build because the optimizing compiler will move your variables around.

Realloc 2D array

I'm starting to learn C and would like input characters from a command line and sort them into an array such that the row number is the ASCII character number and the columns are the index of the character from the input. I know that this must be dynamically done via realloc and malloc but I wouldn't know how to code it up. Could someone help me with this problem?
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define totalASCII 256
int
main(int argc, char **argv) {
int locat;
char current;
int **dRow=NULL;
dRow = malloc(totalASCII*sizeof(*dRow));
for(locat=0;scanf("%c", &current)==1;locat++) {
/* I don't know what to put here */
}
return 1;
}
Your data is so small, there's really no need to allocate it from the heap. Just use an array:
struct { char character; int input_index; } input_data[totalASCII];
On a typical 32-bit system, this will use about 256 * 8 or 2 KB of memory, which really isn't all that much.
Then the storing would be:
for(locat = 0; scanf("%c", &current) == 1; locat++)
{
input_data[locat].character = current;
input_data[locat].input_index = locat;
}
Disclaimer: haven't compiled and run the code.
Try something like this:
int prev_size = 1;
dRow = calloc(totalASCII, sizeof(*dRow)); //use calloc
for(locat=0;scanf("%c", &current)==1;locat++) {
if(dRow[current]) {
prev_size=0;
//try to find how much is already allocated
while(dRow[current][prev_size] != -1)
prev_size++;
dRow[current] = realloc(sizeof(int) * (prev_size+1));
}
else {
prev_size = 1;
dRow[current] = malloc(sizeof(int) * (prev_size+1));
}
dRow[current][prev_size-1] = locat;
dRow[current][prev_size-1] = -1; //end identifier
}
The complexity here is to find the previous allocated size. As there is no other structure/data structure to store this info, this sample code tries to iterate over the array and find -1 which is assumed as end marker.

The showbits() function

While reading a book called "Let us C" I read that a function showbit() exists which can show you the bits of the number. There wasn't any special header file mentioned for it. Searched for it on the internet and didn't found anything useful. Is there such a function? I want this to print the binary of decimal numbers. Else please give me a replacement function. Thanks
All integers are actually in binary in your computer. Its just that it is turned into a string that is the decimal representation of that value when you try to print it using printf and "%d". If you want to know what it looks like in some other base (e.g. base 2 or binary), you either have to provide the proper printf format string if it exists (e.g. "%x" for hex) or just build that string yourself and print it out.
Here is some code that can build the string representation of an integer in any base in [2,36].
#include <stdio.h>
#include <string.h>
char digits[]="01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void reverse(char* start, char* end)
{
for(end--;start<end;start++,end--)
{
char t=*start;
*start=*end;
*end=t;
}
}
int base_change(int n, int base,char* buffer)
{
int pos=0;
if (base>strlen(digits))
return -1;
while(n)
{
buffer[pos]=digits[n%base];
n/=base;
pos++;
}
buffer[pos]='\0';
reverse(buffer,buffer+pos);
return 0;
}
int main()
{
char buffer[32];
int conv=base_change(1024,2,buffer);
if (conv==0) printf("%s\n",buffer);
return 0;
}
You can also try this snippet which uses bit-shifting:
EDIT: (I've made it more portable)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BITS_IN_BYTE 8
#define INTEGRAL_TYPE unsigned int
void showBits(INTEGRAL_TYPE x) {
int i;
static int intSizeInBits = sizeof(INTEGRAL_TYPE) * BITS_IN_BYTE;
static char symbol[2] = {'0','1'};
char * binary = (char*) malloc(intSizeInBits + 1);
memset(binary, 0, intSizeInBits + 1);
for (i=0; i< intSizeInBits; i++) {
binary[intSizeInBits-i-1] = symbol[(x>>i) & 0x01];
}
printf("%s\n", binary);
free(binary);
}
int main() {
showBits(8698513);
return 0;
}
HTH!
This is a very simple solution for printing the bits of an integer
int value = 14;
int n;
for (n=8*sizeof(int)-1;n>=0;n--) {
printf("%d",(value >>n)&1);
}
The book "Let Us C" doesn't define it as a built-in function. The showbits() function is defined in later part of the book as a complete user defined function as I personally went through it. This answer is to anyone who haven't reached that later part of the book and are stuck at the first appearance of the function in the book.
you need to look here
#downvoter It works fine in c also. You just need to reformat your code in c-style.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char buffer[20];
int i = 3445;
_itoa( i, buffer, 2 );
printf("String of integer %d (radix 2): %s",i,buffer);
return 0;
}
*you need to save your file as .c in MSVC++ for _itoa() to work.*
this is the header file for showbits
void showbits(unsigned int x)
{
int i;
for(i=(sizeof(int)*5)-1; i>=0; i--)
(x&(1u<<i))?putchar('1'):putchar('0');
printf("\n");
}
No there is no pre built function and you do not need to include any specific header file.
You will have to provide implementation for function showbits(int).
#include <stdio.h>
void showbits(int);
int main()
{
int j,k;
for(j=0;j<=11;j++)
{
printf("\nBinary value of decimal %d is :",j);
showbits(j);
}
return 0;
}
showbits(int n){
int i,k,andmask;
for(i = 15;i>=0;i--){
andmask = 1<<i;
k = n & andmask;
k==0 ? printf("0"):printf("1");
}
}
If you want to print out the bits of a float, for example you could do something like:
float myFloat = 45.2;
for (int n=0;n<8*sizeof(float);n++) {
printf("%d",(myFloat>>n)&1);
}

Resources