Converting hex to base64 in Objective C?

2019-07-23 05:15发布

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

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

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

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

2条回答
迷人小祖宗
2楼-- · 2019-07-23 05:35
【Aperson】
3楼-- · 2019-07-23 05:41

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.

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];
查看更多
登录 后发表回答