使用OpenSSL的
问题描述:
哎呀iPhone上获取正确HMACSHA1,我的头好痛!使用OpenSSL的
语境
我需要写一些C/Objective-C代码来解密存储在远程服务器上的文件。加密是开源的,并用C#编写
我使用的是从这个项目libssl.a和libcrypto.a;
https://github.com/x2on/OpenSSL-for-iPhone
我的第一个障碍是,即使得到一个字符串的HMACSHA1是正确的:(该SHA1似乎根据参考网站这里是正确的 - http://hash.online-convert.com/sha1-generator但HMAC也不行,所以现在一些。代码;
NSString *input = @"wombats";
// Define some strings etc that we need
unsigned char *inStrg = malloc(256);
inStrg = (unsigned char *)[input UTF8String];
unsigned long lngth = [input length];
unsigned char result [EVP_MAX_MD_SIZE];
unsigned char hmacresult [EVP_MAX_MD_SIZE];
unsigned char newPassPhrase[25];
memset(newPassPhrase, 0, 25);
unsigned char salt[] = "\x01\x02\x03\x04\x05\x06\x07\x08";
// The real code requires us to re-hash the input 1000 times. For now lets
// just check it with 10 (hey even the first is wrong).
for (int i=0; i<10; i++)
{
// Use openssl
SHA_CTX shaContext;
SHA1_Init(&shaContext);
SHA1_Update(&shaContext, inStrg, lngth);
SHA1_Final(result, &shaContext);
unsigned int len;
// If I look at result now, it matches the reference, so I think it is the next stage that goes wrong.
HMAC(EVP_sha1(),salt,8,result,20,hmacresult,&len);
printf("HMAC ----------------- : ");
hexPrint(hmacresult,len);
// Copy the result to the input so we can re-hash;
lngth = len;
memcpy((char *)inStrg,(char *)hmacresult,len);
}
我试图匹配该代码是下面的C#片段此代码生成正确的输出,并从生产服务器的提取物
byte[] salt={0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8};
UTF8Encoding utf8 = new UTF8Encoding();
byte[] data = utf8.GetBytes("wombats");
HMACSHA1 sha1= new HMACSHA1();
sha1.Key = salt;
for(int i=0; i<10; i++)
{
sha1.ComputeHash(data);
data = sha1.Hash;
Console.WriteLine(System.BitConverter.ToString(data));
}
如果我编译并运行C#代码,我得到的输出是以下序列;
DC-F3-1C-C1-2F-8A-86-16-CC-74-1E-DA-25-7B-FF-16-6E-EB-2A-0F
E7-6A-F4-C6-73-07-DB-E8-52-82-9E-D1-96-BF-06-95-85-C6-94-F4
1F-E2-61-BC-F0-08-92-3C-14-70-2B-89-EB-46-C9-20-A5-90-65-9B
etc
如果我看从iPhone版本的输出,我得到以下;
44-35-5b-bb-41-0e-bc-c3-d3-58-62-e6-5c-a0-51-6b-bc-97-11-f6
4c-3b-61-bd-1f-f7-72-13-af-1b-5e-5e-e3-70-8a-31-08-11-67-f2
41-56-8d-41-c1-3e-02-d0-d2-76-ad-d3-49-ba-71-ff-34-d7-3e-8b
etc
因此,显然有严重的错误。
如果我只检查SHA1部分,这似乎是正确的,所以我猜测要么我使用HMAC的错误参数,要么C#HMACSHA1做了与我的期望不同的事情。
我要补充一点,如果我用一个合适的ASCII盐,在线生成的结果,在这里http://hash.online-convert.com/sha1-generator也匹配的C#代码强烈让我怀疑这是我的,这是错误的iPhone℃。
任何人都可以帮助我解决这个难题是什么,我跑出来的,此刻的想法!
答
删除重复的SHA1修复它。 DOH!
SHA_CTX shaContext;
SHA1_Init(&shaContext);
SHA1_Update(&shaContext, inStrg, lngth);
SHA1_Final(result, &shaContext);
删除所有这些。
答
这可能是值得你花时间去使用<CommonCrypto/CommonHMAC.h>
中的方法(不是框架,只是在/usr/include
的标题)。
好,我已经解决了 - DOH!令人惊讶的是,多次将它写出来可以使该便士下降。我是双SHA1哈希 - 下降,它一切正常! – Roger 2011-02-09 19:25:11