How to Hash String using SHA-1 with key?
17,665
Try something like that:
private String sha1(String s, String keyString) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));
return new String( Base64.encodeBase64(bytes));
}
SecretKeySpec docs.
Author by
Ahmad Kayyali
Software Engineer @ Samsung, sometimes musician & guitar teacher
Updated on June 05, 2022Comments
-
Ahmad Kayyali almost 2 years
The time I used to develop applications on iPhone I was converting String to SHA1 with two combination:
- Data
- Key
Now I am developing an Android application and I did not any example for how to calculate SHA1 With key.
I am greatly appreciative of any guidance or help.
[The code that I currently use]private void convertStringToSHA1() { String sTimeStamp = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS").format(new java.util.Date()); String sStringToHash = String.format("%1$s\n%2$s", "Username",sTimeStamp); MessageDigest cript = MessageDigest.getInstance("SHA-1"); cript.reset(); cript.update(sStringToHash.getBytes("utf-8")); sStringToHash = new BigInteger(1, cript.digest()).toString(16); }
-
thejh over 13 yearsWhat code did you use for that conversion?
-
Bozho over 13 yearsSHA-1 with key .. is HMAC? what is the purpose of this?
-
Ahmad Kayyali over 13 years@ thejh i am updating the answer right a way.
-
Ahmad Kayyali over 13 yearsThank you very much for the response, but Base64.encodeBase64 is imported from android.util.Base64 or org.kobjects.base64? thanks in advance.
-
Ahmad Kayyali over 13 yearsJust to let you know the API android.util.Base64 does not have the method you mentioned i used : android.util.Base64.encode(bytes, 0)
-
evilone over 13 yearsIn my example this is imported from org.apache.commons.codec.binary and you can download it from commons.apache.org/codec/download_codec.cgi