将十六进制转换为目标C中的base64? [英] Converting hex to base64 in Objective C?

查看:62
本文介绍了将十六进制转换为目标C中的base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had created a SHA256 encoding of the string using the following function,

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.

It gives me the output : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92. But I need the following output : jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=. It's base64.

如何将生成的十六进制"哈希值转换为"base64"?

How Can I convert the "hex" hash I generated to "base64"?

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

I had use this website to generate base64 hash : http://www.online-convert.com/result/7bd4c809756b3c16cf9d1939b1e57584

推荐答案

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

You should not be converting the NSString *hash that you generated from the description to base-64. It is a hex string, not the actual data bytes.

您应该使用任何可用的base-64编码器直接从 NSData * out 转到base-64字符串.例如,您可以从这篇文章下载实现.a>,并按如下所示使用它:

You should go straight from NSData *out to base-64 string, using any of the available base-64 encoders. For example, you can download an implementation from this post, and use it as follows:

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];

这篇关于将十六进制转换为目标C中的base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆