1

what is alertnate of sha1 function in java

just like in php

sha1("here is string"); 

what will be in java

1
  • 1
    Possible duplicate of Java calculate a sha1 of a String. and many others. Look at the "Related" sidebar in this very question. Commented Apr 19, 2011 at 5:23

2 Answers 2

3

You use the java.security.MessageDigest class in Java. But note that hashes are generally applied to binary data rather than strings - so you need to convert your string into a byte array first, usually with the String.getBytes(String) method - make sure you use the overload which specifies an encoding rather than using the platform default. For example (exception handling elided):

MessageDigest sha1 = MessageDigest.getInstance("SHA1");
byte[] data = text.getBytes("UTF-8");
byte[] hash = sha1.digest(data);

Once you've got the hash as a byte array, you may want to convert that back to text - which should be done either as hex or possibly as Base64, e.g. using Apache Commons Codec.

If you're trying to match the SHA-1 hash produced by PHP, you'll need to find out what encoding that uses when converting the string to bytes, and how it then represents the hash afterwards.

Sign up to request clarification or add additional context in comments.

2 Comments

I was going to suggest a DIY bytes2string function as detailed in this question: stackoverflow.com/questions/521101/… ...
@amir75: I generally prefer using something someone else has already written, but yes, it's not a lot of work in this case :)
0

Here is what I use. (I upvoted the two answers I compiled this one from, but I thought I'd paste it in a single answer for simplicity.)

// This replicates the PHP sha1 so that we can authenticate the same users.
public static String sha1(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    return byteArray2Hex(MessageDigest.getInstance("SHA1").digest(s.getBytes("UTF-8")));
}

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.