iOS HmacSHA1加密

需要导入cocoaSecurity框架

https://github.com/kelp404/CocoaSecurity

Base64:https://github.com/nicklockwood/Base64

导入头文件
#include
#include

具体代码:

001 有加密key Hmac加密处理

/**
 *  对NSString进行处理
 *
 *  @param key  要加密key
*  @param data 加密的data
*
*  @return 加密后的字符串
*/
+(NSString *)HmacSha1:(NSString *)key data:(NSString *)data{
const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];

const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];


uint8_t cHMAC[CC_SHA1_DIGEST_LENGTH];

CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);


//NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];

NSString *hash;

NSMutableString * output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];


for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    
    
[output appendFormat:@"%02x", cHMAC[i]];


hash = output;

return hash;

}

注意事项:需要确认是否需要进行64位处理

002

//HmacSHA1加密;
+(NSString *)HmacSha1:(NSString *)key data:(NSString *)data
{
const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
//Sha256:
// unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
//CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

//sha1
unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                      length:sizeof(cHMAC)];

NSString *hash = [HMAC base64EncodedStringWithOptions:0];//将加密结果进行一次BASE64编码。
return hash;
}

003

//密码加密方式:SHA1
+(NSString *)EncriptPassword_SHA1:(NSString *)password{
 const char *cstr = [password cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:password.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);

NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH *2];

for(int i =0; i < CC_SHA1_DIGEST_LENGTH; i++) {
    [result appendFormat:@"%02x", digest[i]];
}

return [result uppercaseString];
  }

【参考文章】:https://blog.csdn.net/u013056367/article/details/42677033

你可能感兴趣的:(iOS HmacSHA1加密)