c - C中区块链的Nonce函数。C中无符号字符数组的连接
问题描述
我尝试在我的区块链程序中添加一个随机数。但是当我通过尝试重复结果来测试程序性能时(我需要能够验证我的链),我没有得到相同的结果。
首先,我有一个将 a 转换为的structure
函数unsigned array pointer
:
struct Test{
unsigned char data[4];
unsigned char nonce[4];
unsigned char hash[32];
}*prev,*next;
unsigned char *toStringTest(struct Test data)
{
unsigned char *str=malloc(sizeof(unsigned char)*sizeof(data));
memcpy(str,&data,sizeof(data));
return str;
}
然后,我有一个程序给我一个哈希和随机数:
在这个函数中:
- 我将 unsigned char 指针
toStringTest()
与 unsigned char arrat连接起来nonce
。 - 我计算了这个连接的哈希值。
- 如果哈希开始于
0x00
我将哈希和随机数保存到next
块中。如果没有,我重复这个功能。
void hash_with_nonce(struct Test* message,struct Test* new_message){
unsigned char nonce[4]; //number only used once
unsigned char buffer[32];
while(1){
RAND_bytes(nonce, 4); //this function puts 4 cryptographically strong pseudo-random bytes into nonce.
unsigned char* str=toStringTest(*message);
int len = sizeof(unsigned char)*sizeof(*str)+sizeof(unsigned char)*sizeof(nonce);
unsigned char* message_with_nonce = malloc(len);
memcpy(message_with_nonce,str,sizeof(*str));
memcpy(message_with_nonce+sizeof(unsigned char)*sizeof(*str),nonce,sizeof(nonce));
//I concatenated toStringTest(*message) with nonce
SHA256(message_with_nonce, sizeof(message_with_nonce), buffer); //calculation of hash
free(message_with_nonce);
unsigned char var[1] = {0x00}; //rule for nonce decision, I want what hash start by 0x00
if((int *)var[0] == (int *)buffer[0]){
memcpy(new_message->hash,buffer, 32);
memcpy(new_message->nonce, nonce,sizeof(nonce));
return;
}
}
}
这是我的主要内容:
int main(int argc, char **argv)
{
unsigned char hash[32];
prev=malloc(sizeof(struct Test));
RAND_bytes(prev->data, 4);
RAND_bytes(prev->nonce, 4);
SHA256("",sizeof(""),prev->hash);
next=malloc(sizeof(struct Test));
RAND_bytes(next->data, 4);
//I just have filled this block with random data
hash_with_nonce(prev,next);
unsigned char* str=toStringTest(*prev);
int len = sizeof(unsigned char)*sizeof(*str)+sizeof(unsigned char)*sizeof(next->nonce);
unsigned char* message_with_nonce = malloc(len);
memcpy(message_with_nonce,str,sizeof(*str));
memcpy(message_with_nonce+sizeof(unsigned char)*sizeof(*str),next->nonce,sizeof(next->nonce));
SHA256(message_with_nonce, sizeof(message_with_nonce), hash);
}
prev 和 next 只是我用来检查功能hash_with_nonce
是否正常工作的 2 个块。
一个问题是unsigned char hash[32]
main 的 与 不同next->hash
。SHA256() 和 RAND_bytes() 是 openssl 函数。
要检查 2 个哈希是否相同,我有这个功能:
void PrintHex(unsigned char data[], int size)
{
unsigned char tmp[size];
for (int i=0; i<size; i++)
{
sprintf(tmp, "%02x",data[i]);
printf("%s", tmp);
}
printf("\n");
}
解决方案
推荐阅读
- python - 如何在ubuntu的vs代码中写python?
- ruby-on-rails - 如何防止 Rails 模型回调中的查询被 id 过滤
- stm32 - -ffunction-sections -fdata-sections 在 keil
- html - Bootstrap 将图标对齐到按钮的左侧
- c# - 如何在运行时更改 LuisService 的 BING SpellCheck?
- r - 包含三个随机数的随机集(在立方体中采样随机点)
- google-app-engine - 两个应用引擎之间的通信:“安全”环境中的灵活和标准
- java - 根据属性类型获取 XmlElement 或 XmlValue
- javascript - HtmlUnit获取编码错误的字符串
- c++ - 以自定义类为键的 Unordered_map