#include <stdio.h> #include <openssl/bio.h> #include <openssl/rand.h> int rand_test() { char buf[20]; const char* p; unsigned char outBuf[20]; char file[50]; int ret,len; BIO *bio_stdout; //① 方式1
//int RAND_pseudo_bytes(unsigned char *buf, int num);
//RAND_pseudo_bytes() puts num pseudo-random bytes into buf
unsigned char rkey[16]; RAND_pseudo_bytes(rkey, sizeof rkey);
//② 方式2, 最终调用的RAND_bytes产生的随机数。
RAND_screen(); //以屏幕内容作为"seed"产生随机数
strcpy(buf,""); RAND_add(buf,20,strlen(buf)); strcpy(buf,"23424d"); RAND_seed(buf,20); while(1) { ret=RAND_status(); if(ret==1) { printf("seeded enough!\n"); break; } else { printf("not enough sedded!\n"); RAND_poll(); } } /* RAND_file_name() generates a default path for the random seed file. buf points to a buffer of size num in which to store the filename. The seed file is $RANDFILE if that environment variable is set, $HOME/.rnd otherwise. If $HOME is not set either, or num is too small for the path name, an error occurs. */ p=RAND_file_name(file, sizeof(file));
if(p==NULL) { printf("can not get rand file\n"); return -1; }
/* RAND_write_file() writes a number of random bytes (currently 1024) to file filename which can be used to initialize the PRNG by calling RAND_load_file() in a later session. */ ret=RAND_write_file(p);
//PRNG 伪随机数发生器(PRNG)是一个软件,其产生一个被叫做基于一些算法的随机数。
//实际上它不是一个实际的随机数字而是一个伪随机数。最后伪随机数保持对一个度或另一个是可预言的。这个随机数产生器是一个伪随机数产生器。
/* RAND_load_file() reads a number of bytes from file filename and adds them to the PRNG. If max_bytes is non-negative, up to to max_bytes are read; starting with OpenSSL 0.9.5, if max_bytes is -1, the complete file is read. */ len=RAND_load_file(p,1024); ret=RAND_bytes(outBuf, 20); if(ret!=1) { printf("err.\n"); return -1; } bio_stdout=BIO_new(BIO_s_file()); BIO_set_fp(bio_stdout,stdout,BIO_NOCLOSE); BIO_write(bio_stdout,outBuf,20); BIO_write(bio_stdout,"\n",2); BIO_free(bio_stdout); RAND_cleanup(); return 0; }
|