Одноразовая функция блокчейна в C. Конкатенация массива без знака в C - PullRequest
0 голосов
/ 27 марта 2020

Я пытаюсь добавить одноразовый номер в мою программу блокчейна. Но когда я проверяю производительность программы, пытаясь повторить результат (мне нужно уметь проверять цепочку), я не получаю идентичный результат.

Сначала у меня есть функция, которая преобразует 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;
}

Затем у меня есть программа, которая дает мне га sh и nonce:

В этой функции:

  1. Я конкатенировал беззнаковый указатель char из toStringTest() с беззнаковым arrat nonce.
  2. Я вычислил га sh этой конкатенации.
  3. Если ha sh начинается с 0x00 Я сохраняю ха sh и nonce в блоке 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 - это всего лишь 2 блока, которые я использую, чтобы проверить, работает ли функция hash_with_nonce.

Проблема в том, что unsigned char hash[32] основного не совпадает с 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");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...