0

我需要与用作登录名的 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

4

1 回答 1

0

请参阅如何将 NSData 转换为 NSString 十六进制字符串?

我自己使用了一个稍微修改过的版本:

@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
于 2013-04-25T20:39:29.857 回答