开发者

java php sha1 function

开发者 https://www.devze.com 2023-02-26 09:26 出处:网络
what is alertnate of sha1 function in java just like in php sha1(\"here is string\"); what w开发者_C百科ill be in javaYou use the java.security.MessageDigest class in Java. But note that hashes a

what is alertnate of sha1 function in java

just like in php

sha1("here is string"); 

what w开发者_C百科ill 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, 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号