iphone - 在 Objective C 中将十六进制转换为 base64?

标签 iphone objective-c ios xcode sha256

我使用以下函数创建了字符串的 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

最佳答案

您不应该将从描述生成的 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];

关于iphone - 在 Objective C 中将十六进制转换为 base64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11340587/

相关文章:

iphone - cocos2d-x 应用程序的 HTTP 流量在 Charles 代理中不存在

iphone - 在 Interface builder 中放置的 UIView 中,init *真的*发生在哪里?

iphone - 调用已弃用的方法?

ios - 在 Objective c 和 Swift 中你怎么调用它?

iphone - accountTypeWithAccountTypeIdentifier 未完成

ios - 检测何时将 iOS 截图添加到相册

iOS 等同于 onRestart()

iphone - UIScrollView指示器总是显示?

ios - Pushcontroller 类似于呈现 View Controller 的过渡

ios - 在 iOS 的工具栏中包含 UISearchBar