Objective-C 与JAVA的SHA1/HmacSHA1加密算法实现

最近研究IOS手机上登录的功能。由于加密方式使用SHA1算法。网上也没找到直接的例子,最终参照StackoverFlow上的大神,完成了加密实现。

先上代码:

 

 

//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;

}



//密码加密方式: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];

}

 

 

由于Android版本也用到,附上JAVA版本代码:

1.HmacSHA1:

 

 SecretKeySpec localSecretKeySpec = new SecretKeySpec(mySecretKey.getBytes("UTF-8"), "HmacSHA1");//加密密钥

 Mac localMac = Mac.getInstance("HmacSHA1");

 localMac.init(localSecretKeySpec);

 localMac.update(myDate.getBytes("UTF-8"));//加密内容,这里使用时间

 String result = Base64.encodeToString(localMac.doFinal(), 0).trim(); //获取加密结果并转BASE64

 

2:直接SHA1

  

  public static String authPassword(String paramString)

      {

        try

        {

          MessageDigest localMessageDigest = MessageDigest.getInstance("SHA1");

          localMessageDigest.update(paramString.getBytes());

          String str = bytes2Hex(localMessageDigest.digest()).toUpperCase();

          return str;

        }

        catch (NoSuchAlgorithmException localNoSuchAlgorithmException)

        {

        }

        return "";

      }



      public static String bytes2Hex(byte[] paramArrayOfByte)

      {

        String str1 = "";

        for (int i = 0; ; i++)

        {

          if (i >= paramArrayOfByte.length)

            return str1;

          String str2 = Integer.toHexString(0xFF & paramArrayOfByte[i]);

          if (str2.length() == 1)

            str1 = str1 + "0";

          str1 = str1 + str2;

        }

      }

 



 

你可能感兴趣的:(Objective-C)