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