一,问题:
生成32位的随机会话session
二,解决方案:
方案一,用c标准函数的rand()和srand()
方案二,通过使用/dev/random 或者/dev/urandom 来生成随机数
推荐使用方案二,原因如下:
方案一的使用方法如下:
srand(time(NULL));
int rand = rand() % 100;
这里利用了时间种子。但是需要注意的是,当时间种子相当时,那获取到的rand 就会变得不安全。也就时说,如果要有人破解程序时,将此srand(time(NULL));对应的代码改成 srand(1);那么,每次产生的随机数的序列都是一样的。(意思就是,此后rand()%100得到的数和 第一次得到的数都是一样的。)
此外,在某种特定情况下,如果破解者设法使用时钟停止,也可以达到同样的效果。
==》综上,rand() 函数并不安全。
方案二的使用方法如下:
int fd = open("/de/random", O_RDONLY|O_NONBLOCK)
unsigned int rand = 0;
int n = read(fp, &rand, sizeof(rand));
close(fp);
但是由于/dev/random会有卡顿,所以推荐使用/dev/urandom。至于原因,可以看《linxu 系统产生随机数 /dev/random 和 /dev/urandom》
三,实现
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
unsigned int get_int_random_from_rand(int min, int max)
{
if (min > max)
{
swap(min, max);
}
srand((unsigned)time(NULL));
return min + rand()%(max-min+1);
}
unsigned int get_int_random_from_dev(int min, int max)
{
if (min > max)
{
swap(min, max);
}
unsigned int random = 0;
int fd = 0, n = 0;
fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK);
if (fd>0)
{
n = read(fd, &random, sizeof(random));
if (n < sizeof(random))
{
random = 0;
}
close(fd);
}
return min + random%(max-min+1);
}
int main()
{
std::string model("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
std::string session1("");
for (int i = 0; i <model.size(); i++)
{
int flag = get_int_random_from_rand(0, model.size()-1);
session1 += model[flag];
}
cout << "session1:" << session1.c_str()<<endl;
std::string session2("");
for (int i = 0; i <model.size(); i++)
{
int flag = get_int_random_from_dev(0, model.size()-1);
session2 += model[flag];
}
cout << "session2:" << session2.c_str()<<endl;
}