我有一个字符串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