将未签名的char数组转换为char数组

时间:2020-04-12 12:52:30

标签: c hash hashcode sha1

我创建了一个C ++项目,但是我使用C中的CUDA代码。因此,我需要一个将 unsigned char * 转换为 char * 的示例。以下是在C ++中获取哈希的示例,但是在C代码中,我将使用“ malloc”而不是“ new”

程序说明:在程序的输入处接收到需要破解的哈希。我使用hex_to_sting函数将其转换,并将计算出的哈希值与sha1new函数进行比较

我的目标是 对sha1算法进行一些迭代。

示例:

1次迭代:单词“ zzzz” =哈希“ cb990257247b592eaaed54b84b32d96b7904fd95”;

2次迭代:单词“ cb990257247b592eaaed54b84b32d96b7904fd95”-哈希值“ 775a2dae52c3ef080726dd427f81bd482fdf96b5”;

我想将sha1new的输出转换为文本格式,然后再次将其传输到sha1new

sha1算法-从此处进行一些升级的代码:https://github.com/mochimodev/cuda-hashing-algos/blob/master/sha1.cu

sha1new()函数:

__device__ __host__ inline void sha1new(uint8* msg, uint8 length, uint8 sha1[20]) {
    CUDA_SHA1_CTX ctx;
    cuda_sha1_init(&ctx);
    cuda_sha1_update(&ctx, msg, length);
    cuda_sha1_final(&ctx, sha1);
}

hex_to_string:

void hex_to_string(uint8* msg, size_t msg_sz, char* hex, size_t hex_sz)
{
    memset(msg, '\0', msg_sz);
    for (int i = 0; i < hex_sz; i += 2)
    {
        uint8_t msb = (hex[i + 0] <= '9' ? hex[i + 0] - '0' : (hex[i + 0] & 0x5F) - 'A' + 10);
        uint8_t lsb = (hex[i + 1] <= '9' ? hex[i + 1] - '0' : (hex[i + 1] & 0x5F) - 'A' + 10);
        msg[i / 2] = (msb << 4) | lsb;
    }
}

它可以进行一次sha1迭代(不输出“不等于”):

   char* testhash = "cb990257247b592eaaed54b84b32d96b7904fd95";
   char* word = "zzzz";
   unsigned char* sha1hash = new unsigned char[41];
   sha1new((unsigned char*)word, 4, sha1hash);
   uint8 sha1Unhexed[21];
   hex_to_string(sha1Unhexed, 20, testhash, 40);
   for (int i = 0; i < 20; i++)
   {
       if (sha1Unhexed[i] != sha1hash[i])
           std::cout << "not equal" << std::endl;
   }

1 个答案:

答案 0 :(得分:0)

sha1哈希是160位信息,可以存储在20个字节中。由于人类不读取二进制数据,因此通常以十六进制形式打印,从而导致一个40个字符的字符串(范围为0-9和a-f(或A-F))。

您必须意识到哈希算法本身对二进制数据起作用。十六进制形式仅用于打印(或存储在文本文件等中)。

因此,当执行哈希算法的多次迭代时,必须使用二进制数据。之后,您可以将其转换为十六进制格式。

所以,这样的事情(注意:代码没有经过测试,因为我没有sha1new函数):

char * word = "zzzz";
unsigned char * sha1hash = (unsigned char *)malloc(20);
// first iteration has word as input and yields a hash of 160 bits
sha1new(word, strlen(word), sha1hash);
// following iteraitons have the hash as input and a new has as output
for (int i = 1; i < number_of_iterations; i++) {
   sha1new(sha1hash, 20, sha1hash);
   // NOTE: this only works is the sha1new function accepts the same
   // buffer as input and output, otherwise you'd have to make copies
}

// now print the hash
for (int i = 0; i < 20; i++) {
   printf("%02x", (int)sha1hash[i]);
}

// and don't forget to free the memory
free(sha1hash);
sha1hash = NULL;
相关问题