我想用简单的C程序来实现Openssl 里的 EVP _ BytesToKey。
这里有 EVP _ BytesToKey 的伪代码:
/* M[] is an array of message digests
* MD() is the message digest function */
M[0]=MD(data . salt);
for (i=1; i<count; i++) M[0]=MD(M[0]);
i=1
while (data still needed for key and iv)
{
M[i]=MD(M[i-1] . data . salt);
for (i=1; i<count; i++) M[i]=MD(M[i]);
i++;
}
If the salt is NULL, it is not used.
The digests are concatenated together.
M = M[0] . M[1] . M[2] .......
这里的MD()是sha512,我需要的key是32字节,iv是16字节。
下面是我的代码: 假设sha512 是正确的函数;
int main()
{
unsigned long long out[8];
unsigned char key[9] = {0x4b,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c};
int len, i;
len = sizeof(key);
sha512(out, key, len);
unsigned char a[sizeof(out)];
for (i = 0; i < count; i++)
{
long2char(out, a); // unsigned long long to unsigned char;
sha512(out, a, sizeof(out));
}
return 0;
}
for循环里的count是进行sha512的次数。
第一次sha512出来的值就是512位也就是64字节,所以后面每次的结果都是64字节。
我是不是可以认为这已经大于我需要的48字节,也就是上面伪代码里的while循环我可以不需要了?
但是结果是不对的,我不太清楚哪里出了问题,希望各路大神可以给一些意见和建议。
万分感谢!
sha512结果就是64字节,你只用48字节就容易冲突。