Linux平台利用dev/urandom来生成随机数,再转成字符串,以下代码生成的字符串长度为两倍len.
dev/random和/dev/urandom是Linux系统中提供的随机伪设备,这两个设备的任务,是提供永不为空的随机字节数据流。很多解密程序与安全应用程序(如SSH Keys,SSL Keys等)需要它们提供的随机数据流。
#include"log_uuid.h"
#include <stdlib.h>
#include <unistd.h>
#include<fcntl.h>
std::string getUUID(unsigned int len) {
std::string str;
unsigned char* buffer = new unsigned char[len+1];
char* uuid = new char [2*len+1];
int fd = open("/dev/urandom", O_RDONLY);
if (read(fd, buffer, len) == len) {
for(int i=0;i<len;i++)
sprintf(uuid+i*2, "%02X",buffer[i]);
uuid[2*len] = '\0';
str = uuid;
} else {
printf("Error: GetUnique %d\n", __LINE__);
}
delete [] buffer;
delete [] uuid;
return str;
}
另一方法,生成最大长度为maxlen的随机长度的随机字符串
std::string randstr(int max_len)
{
int real_len = rand() % max_len;
if(real_len == 0) return "";
char* str = (char*)malloc(real_len);
for (int i = 0; i < real_len; ++i)
{
switch ((rand() % 3))
{
case 1:
str[i] = 'A' + rand() % 26;
break;
case 2:
str[i] = 'a' + rand() % 26;
break;
default:
str[i] = '0' + rand() % 10;
break;
}
}
str[real_len -1] = '\0';
std::string string = str;
free(str);
return string;
}
|