2012-04-16 46 views
0

我正嘗試從本機iPhone應用程序與C#服務進行通信。爲了傳達輸入的密碼需要進行散列並與存儲在服務器上的散列版本進行比較。我試圖重新創建目標C C#的哈希值,這就是它開始變得有趣C#MD5和Objective C之間的差異MD5

目標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的MD5部分之前。使用虛擬數據提供的則返回:

74 
65 
73 
74 
50 
61 
73 
73 
31 
32 
33 
19 
aa 
db 
6a 
07 
b5 
db 

不過,後來我回去不同的價值觀和我不知道從哪裏裏去。

任何人有任何想法?隨意指出我做錯的事情。謝謝。

回答

1

我懷疑你的錯誤是CC_MD5的第二個參數應該是輸入而不是輸出長度。通過輸入長度應該可以解決您的直接問題。

但我認爲,你應該扔掉兩邊的代碼,並使用一些功能設計的密碼散列。如PBKDF2或bcrypt。

將散列發送到服務器也很奇怪。通常你將密碼發送到服務器並在那裏進行散列。發送哈希本質上改變了密碼的定義,並允許登錄攻擊者誰不知道密碼,但知道哈希。

+0

你能解釋一下,如何發送哈希到服務器不太安全,然後發送密碼?攻擊者將如何知道散列?即使他們確實知道散列,他們將如何讓他們登錄? – 2012-04-16 22:38:30

+2

如果攻擊者危害你的數據庫,他會知道所有用戶的哈希值,並且可以登錄任何用戶。如果您要發送密碼,則無法在不顛倒散列的情況下登錄。 – CodesInChaos 2012-04-16 22:41:16

+2

「即使他們確實知道散列,他們將如何讓他們登錄?」通過發送哈希到服務器就像正常登錄一樣?我真的不明白你的問題。 – CodesInChaos 2012-04-16 22:42:00