Skip to content

Instantly share code, notes, and snippets.

@giraam
Last active May 17, 2023 17:55
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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;
}
@arabovs
Copy link

arabovs commented Dec 15, 2017

simple and easy to understand, thanks

@alexec
Copy link

alexec commented May 25, 2018

I'd like to report this gist ... as being awesome!

@Juliet-Selebalo
Copy link

Juliet-Selebalo commented Jul 26, 2018

@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