Recently researched the ability to sign in on an iOS phone. The SHA1 algorithm is used because of encryption. The net also did not find the direct example, the final reference StackOverflow on the big God, completed the encryption implementation.
First on the code:
//HmacSHA1 encryption;
+(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];//Encode the encryption result in BASE64.
Return hash;
}
/ / Password encryption method: 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];
}
Since the Android version is also used, attach the Java version code:
1.HMACSHA1:
SecretKeySpec localSecretKeySpec = new SecretKeySpec(mySecretKey.getBytes("UTF-8"), "HmacSHA1");//Encryption key
Mac localMac = Mac.getInstance("HmacSHA1");
localMac.init(localSecretKeySpec);
localMac.update(myDate.getBytes("UTF-8"));//Encrypted content, use time here
String result = Base64.encodeToString(localMac.doFinal(), 0).trim(); //Get the encryption result and transfer to BASE64
2: Direct 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;
}
}
Implementation of SHA1/HMACSHA1 encryption algorithm for OBJECTIVE-C and Java