Skip to content

Instantly share code, notes, and snippets.

@giraam
Last active May 17, 2023 17:55
Show Gist options
  • Save giraam/7413306 to your computer and use it in GitHub Desktop.
Save giraam/7413306 to your computer and use it in GitHub Desktop.
Hashing a String with SHA1 in Java
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;
}
@DamianFekete
Copy link

DamianFekete commented Feb 21, 2019

Guava may be nicer to use: https://github.com/google/guava/wiki/HashingExplained
Something like:

      Hashing.sha256()
            .hashString(input, Charsets.UTF_8)
            .toString();

(yes, there is still a SHA-1 there)

@eduardo-mior
Copy link

Parabéns. Muito bom!

@Edsuns
Copy link

Edsuns commented Nov 3, 2020

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