[英]Discrepancy between C# MD5 and Objective C MD5
我正在嘗試通過本機iPhone應用程序與C#服務進行通信。 為了進行通信,需要對輸入的密碼進行哈希處理,並與存儲在服務器上的哈希版本進行比較。 我正在嘗試在Objective C中重新創建C#哈希,這就是它開始變得有趣的地方
目標C代碼:
NSString * password = @"testPass123";
const char *cPassword = [password UTF8String];
NSString * key = @"Garbage12345";
NSData * keyData = [NSData dataFromBase64String:key];
NSUInteger len = [keyData length];
unsigned char * cKey = (unsigned char *)malloc(len);
memcpy(cKey, [keyData bytes], len);
// Concatenate into one byte array
unsigned char totalString[18];
for (int i = 0; i < strlen(cPassword); i++) {
totalString[i] = cPassword[i];
}
for (int i = 0; i < len; i++) {
totalString[strlen(cPassword) + i] = cKey[i];
}
// DEBUG: Display byte array
for (int i = 0; i < 18; i++) {
NSLog(@"totalString: %x", totalString[i]);
}
// **** totalString == plainTextWithSaltBytes from the C# portion ****
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(totalString, CC_MD5_DIGEST_LENGTH, result);
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
NSLog(@"result: %02x", result[i]);
}
C#代碼:
byte[] SaltBytes = Convert.FromBase64String("Garbage12345");
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes("testPass123");
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + SaltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < SaltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = SaltBytes[i];
HashAlgorithm hash = new MD5CryptoServiceProvider();
// **** plainTextWithSaltBytes == totalString from the Obj-C portion ****
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(hashBytes);
在字節數組進入任何一個的MD5部分之前,我會得到相同的結果。 使用提供的偽數據,它返回:
74
65
73
74
50
61
73
73
31
32
33
19
aa
db
6a
07
b5
db
但是,此后我得到了不同的值,並且不確定從那里去哪里。
有人有想法么? 隨時指出我做錯的事情。 謝謝。
我懷疑您的錯誤是CC_MD5
的第二個參數應該是輸入長度,而不是輸出長度。 輸入長度可以解決您的直接問題。
但是我認為,您應該丟掉兩邊的代碼,並使用一些設計用於密碼哈希的函數。 例如PBKDF2或bcrypt。
您將哈希發送到服務器也很奇怪。 通常,您將密碼發送到服務器並在其中進行哈希處理。 發送哈希從本質上改變了密碼的定義,並允許不知道密碼但知道哈希的攻擊者登錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.