MD5/SHA1/Hmac_SHA1

Posted 小师傅啊小师傅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MD5/SHA1/Hmac_SHA1相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

vs 2010代码片段

vs 2010代码片段

1 代码片段1

sublime text3 增加代码片段(snipper)

web代码片段

JavaScript单行代码,也就是代码片段