我在使用SHA1散列一些字符串时遇到问题:C#和Objective C正在产生不同的结果。
目标C:
- (void) hashSHA1:(NSString*)input salt:(NSString*)salt
{
const char *cstr = [[NSString stringWithFormat:@"%@%@",input, salt] cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
NSLog("%@ : %@", input,output);
}
输出:
[self hashSHA1:@"F66791B5-33F1-49BB-AAA9-1D7A1CE51752" salt:@"salt"];
//Show : F66791B5-33F1-49BB-AAA9-1D7A1CE51752 : 435ba79fde87c45150fd053ca43ecce92fac54d3
C#:
static void HashSha1(string uid, string salt)
{
var data = Encoding.UTF8.GetBytes(uid + salt);
var sha1 = new SHA1CryptoServiceProvider();
var hash = sha1.ComputeHash(data);
var sb = new StringBuilder();
foreach (var b in hash)
{
sb.Append(b.ToString("x2"));
}
Console.WriteLine("{0} : {1}", uid,sb.ToString());
}
输出:
HashSha1("F66791B5-33F1-49BB-AAA9-1D7A1CE51752", "salt");
//Show : F66791B5-33F1-49BB-AAA9-1D7A1CE51752 : 0853829f9df35d4171b7aff44ed62f0747523a3f
我在这里错过了什么吗?
谢谢!
答案 0 :(得分:1)
看看这一系列的Objective-C代码,并承认对Objc不太了解,不应该这一行:
NSData *data = [NSData dataWithBytes:cstr length:input.length];
读:
NSData *data = [NSData dataWithBytes:cstr length:strlen(cstr)];