我有一個字符串MD5與ASCII字符
wDevCopyright = [NSString stringWithFormat:@"Copyright: %c 1995 by WIRELESS.dev, Corp Communications Inc., All rights reserved.",0xa9];
,並Munge時間它我打電話
-(NSString *)getMD5:(NSString *)source
{
const char *src = [source UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(src, strlen(src), result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
]; //ret;
}
因爲0xa9的* SRC = [來源UTF8字符串]不創建一個代表串字符,因此返回了一個與其他平臺無法比擬的模式。
我試圖用NSASCIIStringEncoding對字符進行編碼,但它破壞了代碼。
如何用具有ASCII字符的字符串調用CC_MD5並獲得與Java中相同的哈希值?
更新到代碼請求:
爪哇
private static char[] kTestASCII = {
169
};
System.out.println("\n\n>>>>> msg## " + (char)0xa9 + " " + (char)169 + "\n md5 " + md5(new String(kTestASCII), false) //unicode = false
結果>>>>> MSG ## \ 251 \ 251 MD5 a252c2c85a9e7756d5ba5da9949d57ed
ObjC
char kTestASCII [] = {
169
};
NSString *testString = [NSString stringWithCString:kTestASCII encoding:NSUTF8StringEncoding];
NSLog(@">>>> objC msg## int %d char %c md5: %@", 0xa9, 169, [self getMD5:testString]);
結果>>>> objC msg ## int 169 char©md5:9b759040321a408a5c7768b4511287a6
**如前所述 - 沒有0xa9,Java和ObjC中的哈希值是相同的。我試圖獲得哈希值0xa9 Java和ObjC
Java的MD5碼相同
private static char[] kTestASCII = {
169
};
md5(new String(kTestASCII), false);
/**
* Compute the MD5 hash for the given String.
* @param s the string to add to the digest
* @param unicode true if the string is unciode, false for ascii strings
*/
public synchronized final String md5(String value, boolean unicode)
{
MD5();
MD5.update(value, unicode);
return WUtilities.toHex(MD5.finish());
}
public synchronized void update(String s, boolean unicode)
{
if (unicode)
{
char[] c = new char[s.length()];
s.getChars(0, c.length, c, 0);
update(c);
}
else
{
byte[] b = new byte[s.length()];
s.getBytes(0, b.length, b, 0);
update(b);
}
}
public synchronized void update(byte[] b)
{
update(b, 0, b.length);
}
//--------------------------------------------------------------------------------
/**
* Add a byte sub-array to the digest.
*/
public synchronized void update(byte[] b, int offset, int length)
{
for (int n = offset; n < offset + length; n++)
update(b[n]);
}
/**
* Add a byte to the digest.
*/
public synchronized void update(byte b)
{
int index = (int)((count >>> 3) & 0x03f);
count += 8;
buffer[index] = b;
if (index >= 63)
transform();
}
我相信我的問題是使用NSData的withEncoding,而不是一個C的char []或Java byte []。那麼在objC中將自己的字節轉換爲byte []的最佳方法是什麼?
你能請註明你的問題?我們希望看到明確的問題。 – Oded 2010-11-21 14:13:37
謝謝你指導我成爲一個更好的名單公民。 – 2010-11-21 14:46:42
你的Java代碼是什麼樣的? – 2010-11-21 23:25:47