我在使用SHA1對一些字符串進行散列時遇到了問題:C#和Objective C正在產生不同的結果。在Objective-C和C#中產生不同結果的SHA1
目標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
我在這裏錯過了什麼嗎?
謝謝!
您可以在調用散列函數之前驗證'data'是否包含相同的值? –
確實!調用sha1.ComputeHash(data)後數據值沒有改變! –
不,我的意思是數據在兩段代碼中都包含相同的值,而不是在調用散列函數之前和之後 –