简体   繁体   中英

java php sha1 function

what is alertnate of sha1 function in java

just like in php

sha1("here is string"); 

what will be in java

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, eg 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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM