我有一个字符串
wDevCopyright = [NSString stringWithFormat:@"Copyright: %c 1995 by WIRELESS.dev, Corp Communications Inc., All rights reserved.",0xa9];
并且我打电话给我
-(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 = [source UTF8String]没有创建表示字符串的字符,因此返回一个与其他平台无法比较的munge。
我尝试使用NSASCIIStringEncoding对char进行编码,但它破坏了代码。
如何使用包含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中的哈希值是相同的。我试图在Java和ObjC中得到0xa9的哈希值相同
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 []的最佳方法是什么?
答案 0 :(得分:2)
答案 1 :(得分:0)
stringWithCString
需要空终止的C-String。我不认为kTestASCII[]
在Objective-C代码中必然以null结尾。也许这就是差异的原因。
尝试:
char kTestASCII [] = {
169,
0
};
答案 2 :(得分:0)
感谢GBegan的解释 - 这是我的解决方案
for(int c = 0; c < [s length]; c++){
int number = [s characterAtIndex:c];
unsigned char c[1];
c[0] = (unsigned char)number;
NSMutableData *oneByte = [NSMutableData dataWithBytes:&c length:1];
}