我正在尝试从原生 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
但是,之后我得到了不同的值,不知道从那里去哪里。
有人有想法么?随时指出我做错的事情。谢谢。