我需要实现特定散列函数的迭代应用,例如SHA1,输入x n次,有效,即SHA1(... SHA1(SHA1(x)))。我正在尝试使用下面的代码进行此操作,但对于n = 2 ^ 16,这个速度非常慢2秒。在下面的代码中,$ n $是应用SHA1的次数,x = seedj1和temp = SHA1(... SHA1(SHA1(x)))。你可以帮帮我吗?
int hashcwe_n1(int n, unsigned char * seedj1, unsigned char * temp) {
int i, j;
int r = 160;
memcpy(temp, seedj1, r);
for (i = 0; i < n; i++) {
SHA1(seedj1, r, temp);
if (n % 2 != 0)
swapStrings(&temp, &seedj1);
else {
if (i == n - 1) {
memcpy(seedj1, R, r);
} else {
swapStrings(&temp, &seedj1);
}
}
}
return 1;
}
void swapStrings(unsigned char** a, unsigned char** b) {
unsigned char *temp = *a;
*a = *b;
*b = temp;
}
答案 0 :(得分:3)
我不相信你的算法是正确的,所以测量它的性能有点类似于在母鸡产卵之前计算鸡,更不用说在蛋孵化之前。
除非......
,否则迭代工作负载功能没有理由表现出如此糟糕的性能以下是一个应该是正确的夹具,并且表现出可接受的性能(至少在我看来)。使用的测试机器的相关数据:
来源
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <openssl/sha.h>
// simple hex-print utility
void hex_print(const void *buf, size_t n)
{
const unsigned char *beg = buf, *end = beg+n;
while (beg != end)
printf("%02x", *beg++);
fputc('\n', stdout);
}
// iterate n-times
void hashcwe_n
(
unsigned short n, // iteration count
void *src, // source bytes
size_t slen, // souce length
void *dst // target buffer
)
{
unsigned char md1[SHA_DIGEST_LENGTH];
unsigned char md2[SHA_DIGEST_LENGTH];
unsigned char *p1 = md1, *p2 = md2;
unsigned short i;
if (n == 0)
return;
// perform initial digest
SHA1(src, slen, md1);
// iterate the remainder of the loop
for (i=0; i<(n-1); ++i)
{
unsigned char *tmp = p1;
SHA1(p1, SHA_DIGEST_LENGTH, p2);
p1 = p2;
p2 = tmp;
}
memcpy(dst, p1, SHA_DIGEST_LENGTH);
}
// main entry point
int main()
{
unsigned char data[] = {0x61,0x62,0x63}; // "abc"
unsigned char md[SHA_DIGEST_LENGTH] = {0};
hashcwe_n(USHRT_MAX, data, sizeof(data), md);
hex_print(md, SHA_DIGEST_LENGTH);
return 0;
}
构建命令
clang -std=c11 -O2 -Wall -Wextra -pedantic -lcrypto -o sample sample.c
输出控制台
$ time ./sample
a21b4b42e20066a1046d3c81b42b7cd8a6403bf2
real 0m0.031s
user 0m0.026s
sys 0m0.003s
See here同样的样本在Coliru上运行。
祝你好运