Last active
May 17, 2023 17:55
-
-
Save giraam/7413306 to your computer and use it in GitHub Desktop.
Hashing a String with SHA1 in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.logging.*; | |
import javax.xml.bind.DatatypeConverter; | |
/** | |
* Hashing with SHA1 | |
* | |
* @param input String to hash | |
* @return String hashed | |
*/ | |
public String sha1(String input) { | |
String sha1 = null; | |
try { | |
MessageDigest msdDigest = MessageDigest.getInstance("SHA-1"); | |
msdDigest.update(input.getBytes("UTF-8"), 0, input.length()); | |
sha1 = DatatypeConverter.printHexBinary(msdDigest.digest()); | |
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { | |
Logger.getLogger(Encriptacion.class.getName()).log(Level.SEVERE, null, e); | |
} | |
return sha1; | |
} |
Parabéns. Muito bom!
There is a problem: input.getBytes("UTF-8").length
and input.length()
are not always equal.
It's better to replace the 15th line with msdDigest.update(input.getBytes("UTF-8"));
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Guava may be nicer to use: https://github.com/google/guava/wiki/HashingExplained
Something like:
(yes, there is still a SHA-1 there)