1

what is alertnate of sha1 function in java

just like in php

sha1("here is string"); 

what will be in java

user713085
  • 61
  • 1
  • 4
  • 1
    Possible duplicate of [Java calculate a sha1 of a String.](http://stackoverflow.com/questions/4400774/java-calculate-a-sha1-of-a-string) and many others. Look at the "Related" sidebar in this very question. – deceze Apr 19 '11 at 05:23

2 Answers2

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I was going to suggest a DIY bytes2string function as detailed in this question: http://stackoverflow.com/questions/521101/using-sha1-and-rsa-with-java-security-signature-vs-messagedigest-and-cipher ... – laher Apr 19 '11 at 05:29
  • @amir75: I generally prefer using something someone else has already written, but yes, it's not a lot of work in this case :) – Jon Skeet Apr 19 '11 at 05:31
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();
}
11101101b
  • 7,679
  • 2
  • 42
  • 52