1. 程式人生 > >MD5/SHA1/Hmac_SHA1

MD5/SHA1/Hmac_SHA1

char nsdata SM odi utf cdata with crypto input

1、MD5

#import <CommonCrypto/CommonDigest.h>
+ (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest ); // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2
]; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; }

2、SHA1

+ (NSString *) sha1:(NSString *)input{
     NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, (unsigned 
int)data.length, digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) { [output appendFormat:@"%02x", digest[i]]; } return output; }

3、HmacSHA1

//額外添加了base64轉碼
+(NSString *)Base_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)];

  //將加密結果進行一次BASE64編碼。
  NSString *hash = [HMAC base64EncodedStringWithOptions:0];
  return hash;
}

MD5/SHA1/Hmac_SHA1