Skip to content

Instantly share code, notes, and snippets.

@indywidualny
Created December 14, 2015 14:26
Show Gist options
  • Save indywidualny/61312f62a1932ef4ae84 to your computer and use it in GitHub Desktop.
Save indywidualny/61312f62a1932ef4ae84 to your computer and use it in GitHub Desktop.
String to SHA-1
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
public static void main(String[] args) {
String plain = "example";
System.out.println("Plain: " + plain);
try {
System.out.println("SHA-1: " + AeSimpleSHA1.SHA1(plain));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
}
class AeSimpleSHA1 {
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (byte b : data) {
int halfbyte = (b >>> 4) & 0x0F;
int two_halfs = 0;
do {
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("UTF-8"), 0, text.getBytes("UTF-8").length);
byte[] sha1hash = md.digest();
return convertToHex(sha1hash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment