C#MD5和Objective C MD5之间的差异

时间:2012-04-16 22:23:33

标签: c# objective-c web-services 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

然而,之后我回到了不同的价值观,我不确定从那里去哪里。

有人有什么想法吗?随意指出我做错的事情。感谢。

1 个答案:

答案 0 :(得分:1)

我怀疑你的错误是CC_MD5的第二个参数应该是输入而不是输出长度。传入输入长度可以解决您当前的问题。

但我认为,你应该抛弃双方的代码,并使用一些专为密码散列设计的功能。如PBKDF2或bcrypt。

将散列发送到服务器也很奇怪。通常,您将密码发送到服务器并在那里哈希。发送哈希本质上改变了密码的定义,并允许登录不知道密码但知道哈希的攻击者。

相关问题