2013-04-25 135 views
0

我有一個需要與作爲登錄的Web服務集成。散列需要在客戶端上生成。我能夠產生正確的散列作爲NSMutableData,但是隨後我需要將它轉換爲字符串,而不會在輸出控制檯中將NSMutableData對象呈現爲字符串時產生空格或括號。我已經閱讀了幾篇文章,看起來都是這麼說的:將Sha256哈希值轉換爲NSString


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

Base64編碼。 – 2013-04-25 20:29:16

+0

@HotLicks:不,那只是十六進制,而不是base64。 – duskwuff 2013-04-25 21:52:55

回答

0

How to convert an NSData into an NSString Hex string?

我用稍作修改的版本sion我自己:

@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 
+0

這可能是一個真正的新手評論,但是當我使用它時,我的哈希會返回所有大寫。我怎麼能讓它不這樣做? – Pheepster 2013-04-25 21:42:37

+0

原始版本在所有上限中都返回哈希值,我在版本中添加了一個參數(大寫)來控制該哈希值。 – leafduo 2013-04-25 21:49:42