传入字符串,输出它的base64编码结果
- (NSString *)getEncryption:(NSString *)data secret:(NSString *)secret{
//传入 需要编码的数据
NSString* key = secret; //key固定
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; //转换为二进制数据
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *hash = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; //得到一个hash二进制数
//调用类方法,参数为hash,进行数据编码,返回编码结果
NSString *result = [PDEncryptionTools base64forData:hash];
return [result stringByReplacingOccurrencesOfString:@"+" withString:@"_"];
}
进行base64编码
+ (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes]; //数据 字节 类型转换为 8位2进制
NSInteger length = [theData length]; //数据的长度
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; //返回加密的数据
}
密钥
#define SECRET @"8b11c62e-2dfe-4921-b108-d9fd621ce7e5"
需要引入:
<Foundation/Foundation.h>、<CommonCrypto/CommonHMAC.h>