In Objective C I've been using the following code to hash a string:
-(NSString *) sha1:(NSString*)stringToHash {
const char *cStr = [stringToHash UTF8String];
unsigned char result[20];
CC_SHA1( cStr, strlen(cStr), result );
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15],
result[16], result[17], result[18], result[19]
];
}
Now I need the same for Android but can't find out how to do it. I've been looking for example at this: Make SHA1 encryption on Android? but that doesn't give me the same result as on iPhone. Can anyone point me in the right direction?
The method you are looking for is not specific to Android, but to Java in general. You're looking for the MessageDigest (
import java.security.MessageDigest
).An implementation of a
sha512(String s)
method can be seen here, and the change for a SHA-1 hash would be changing line 71 to:You don't need andorid for this. You can just do it in simple java.
Have you tried a simple java example and see if this returns the right sha1.
Also share what your expected sha1 should be. Maybe ObjectC is doing it wrong.
A simpler SHA-1 method: (updated from the commenter's suggestions, also using a massively more efficient byte->string algorithm)
Android comes with Apache's Commons Codec - or you add it as dependency. Then do:
That is the old deprecated method you get with Android 4 by default. The new versions of DigestUtils bring all flavors of shaHex() methods like sha256Hex() and also overload the methods with different argument types.
http://commons.apache.org/proper/commons-codec//javadocs/api-release/org/apache/commons/codec/digest/DigestUtils.html