安全随机数产生器

随机数产生器

在这里插入图片描述

//规则13: 包含10个或更多随机十六进制数,(随机数限制:0-9 ,A-F), 长度 10-16 , 默认是10
void pwd_rule_thirteen(char *fixed, char *head, char *value, int len)
{
    char lengthstr[8] = "";
    char length = 10;
    unsigned char random_value[16] = "";
    char randomstr[33] = "";
    int i = 0;
    int dev_random_fd = -2;
    char* next_random_byte;
    int bytes_to_read;
    
    if ( !fixed || !head || !value  ) {
        debug("param fixed or head or value is NULL \n");
        return ;
    }
    
    cfgd_read_value_by_config_name("SYS_WIFI_PWD_LENGTH", lengthstr, sizeof(lengthstr) );
    if ( strlen(lengthstr) ) {
        length = atoi(lengthstr);
        if ( 16 < length ) {
            length = 16;
        }
    }
    
    if ( length < len ) {
        debug("len is too short , length : %d but len : %d \n" ,  length , len );
    }
    
    
    if (dev_random_fd == -2)
    {
        dev_random_fd = open("/dev/random", O_RDONLY);
        
        if(-1 == dev_random_fd) {
            debug("read /dev/random failed \n");
            dev_random_fd = open("/dev/urandom", O_RDONLY);
        }
        
        if(-1 == dev_random_fd) {
            debug("read /dev/urandom failed \n");
            return ;
        }
    }
    
    next_random_byte = (char*) &random_value;
    
    bytes_to_read = sizeof (random_value);
    
    do {
        
        int bytes_read;
        
        bytes_read = read (dev_random_fd, next_random_byte, bytes_to_read);
        
        bytes_to_read -= bytes_read;
        
        next_random_byte += bytes_read;
        
    } while (bytes_to_read > 0);
    
    close(dev_random_fd);
    
    
    for(i = 0; i < sizeof(random_value); i++)
    {
        sprintf(randomstr + i * 2, "%02X", random_value[i]);
    }
    randomstr[32] = '\0';
    
    snprintf(value, length, "%s%c", randomstr , '\0' );

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值