我需要与作为登录的Web服务集成。需要在客户端上生成哈希。我能够生成正确的哈希作为NSMutableData,但后来我需要将它转换为字符串,而不会在输出控制台中将NSMutableData对象呈现为字符串时产生空格或括号。我看过几篇帖子,似乎都说了同样的话:
NSString *newstring = [[NSString alloc] initWithDSata:dataToConvert encoding:NSUTF8StringEncoding];
不幸的是,这对我不起作用。使用NSUTF8StringEncoding返回null。 NSASCIIStringEncoding更糟糕。
这是我的代码:
NSString *password = [NSString stringWithFormat:@"%@%@", kPrefix, [self.txtPassword text]];
NSLog(@"PLAIN: %@", password);
NSData *data = [password dataUsingEncoding:NSASCIIStringEncoding];
NSMutableData *sha256Out = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes, data.length, sha256Out.mutableBytes);
NSString *preppedPassword = [[NSString alloc] initWithData:sha256Out encoding:NSASCIIStringEncoding];
NSLog(@"HASH: %@\n", preppedPassword);
如何将NSMutableData转换为字符串?
我的问题是我需要从这个
< 7e8df5b3 17c99263 e4fe6220 bb75b798 4a41de45 44464ba8 06266397 f165742e>
到这个
7e8df5b317c99263e4fe6220bb75b7984a41de4544464ba806266397f165742e
答案 0 :(得分:0)
请参阅How to convert an NSData into an NSString Hex string?
我自己使用了一个稍微修改过的版本:
@implementation NSData (Hex)
- (NSString *)hexRepresentationWithSpaces:(BOOL)spaces uppercase:(BOOL)uppercase {
const unsigned char *bytes = (const unsigned char *)[self bytes];
NSUInteger nbBytes = [self length];
// If spaces is true, insert a space every this many input bytes (twice this many output characters).
static const NSUInteger spaceEveryThisManyBytes = 4UL;
// If spaces is true, insert a line-break instead of a space every this many spaces.
static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
NSUInteger strLen = 2 * nbBytes + (spaces ? nbBytes / spaceEveryThisManyBytes : 0);
NSMutableString *hex = [[NSMutableString alloc] initWithCapacity:strLen];
for (NSUInteger i = 0; i < nbBytes; ) {
if (uppercase) {
[hex appendFormat:@"%02X", bytes[i]];
} else {
[hex appendFormat:@"%02x", bytes[i]];
}
// We need to increment here so that the every-n-bytes computations are right.
++i;
if (spaces) {
if (i % lineBreakEveryThisManyBytes == 0) {
[hex appendString:@"\n"];
} else if (i % spaceEveryThisManyBytes == 0) {
[hex appendString:@" "];
}
}
}
return hex;
}
@end