Last active
November 20, 2016 11:27
-
-
Save VictorZhang2014/5794a859722523d65767dc97abf906f2 to your computer and use it in GitHub Desktop.
iOS/C Hmac+SHA256 Encryption
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <CommonCrypto/CommonDigest.h> | |
#include <CommonCrypto/CommonHMAC.h> | |
@interface ZRCommonCryption : NSObject | |
/** | |
* 加密方式,MAC算法: HmacSHA256 | |
* | |
* @param plaintext 要加密的文本 | |
* @param key 秘钥 | |
* | |
* @return 加密后的字符串 | |
*/ | |
+ (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key; | |
@end | |
@implementation ZRCommonCryption | |
+ (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key | |
{ | |
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; | |
const char *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding]; | |
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; | |
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); | |
NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)]; | |
const unsigned char *buffer = (const unsigned char *)[HMACData bytes]; | |
NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2]; | |
for (int i = 0; i < HMACData.length; ++i){ | |
[HMAC appendFormat:@"%02x", buffer[i]]; | |
} | |
return HMAC; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment