【问题标题】:Converting hex to base64 in Objective C?在Objective C中将十六进制转换为base64?
【发布时间】:2012-07-05 18:42:41
【问题描述】:

我使用以下函数创建了字符串的 SHA256 编码,

const char *s=[@"123456" cStringUsingEncoding:NSASCIIStringEncoding];
    NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];

    uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
    CC_SHA256(keyData.bytes, keyData.length, digest);
    NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
    NSString *hash=[out description];
    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];

    NSLog(@"Hash : %@", hash);

它给了我输出:8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92。 但我需要以下输出:jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=。它是 base64。

如何将我生成的“hex”哈希转换为“base64”?

我曾使用此网站生成 base64 哈希:http://www.online-convert.com/result/7bd4c809756b3c16cf9d1939b1e57584

【问题讨论】:

标签: iphone objective-c ios xcode sha256


【解决方案1】:

您不应该将您从描述中生成的NSString *hash 转换为base-64。它是一个十六进制字符串,而不是实际的数据字节。

您应该使用任何可用的 base-64 编码器直接从 NSData *out 转到 base-64 字符串。例如,您可以从this post 下载一个实现,并按如下方式使用它:

const char *s=[@"123456" cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];

uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
CC_SHA256(keyData.bytes, keyData.length, digest);
NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
// The method below is added in the NSData+Base64 category from the download
NSString *base64 =[out base64EncodedString];

【讨论】:

    【解决方案2】:

    我用这个,(在How do I do base64 encoding on iphone-sdk?中提到)

    http://www.imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php

    效果很好,并且很容易与 ARC 一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2021-06-26
      • 2017-07-31
      相关资源
      最近更新 更多