Last active
July 26, 2016 22:45
-
-
Save qpark99/7652032 to your computer and use it in GitHub Desktop.
Java MD5, SHA256 Hash
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
public static String md5(String s) | |
{ | |
try | |
{ | |
// Create MD5 Hash | |
MessageDigest digest = MessageDigest.getInstance("MD5"); | |
digest.update(s.getBytes(Charset.forName("UTF-8"))); | |
byte messageDigest[] = digest.digest(); | |
// Create Hex String | |
StringBuffer hexString = new StringBuffer(); | |
for (int i=0; i<messageDigest.length; i++) | |
{ | |
String hex = Integer.toHexString(0xFF & messageDigest[i]); | |
if(hex.length()==1) | |
{ | |
hexString.append('0'); | |
} | |
hexString.append(hex); | |
} | |
return hexString.toString(); | |
} | |
catch (NoSuchAlgorithmException e) | |
{ | |
e.printStackTrace(); | |
} | |
return ""; | |
} | |
public static String sha256(String s) | |
{ | |
String result = ""; | |
try | |
{ | |
MessageDigest md = MessageDigest.getInstance("SHA-256"); | |
md.update(s.getBytes(Charset.forName("UTF-8"))); | |
byte byteData[] = md.digest(); | |
StringBuffer hexString = new StringBuffer(); | |
for (int i=0;i<byteData.length;i++) | |
{ | |
String hex=Integer.toHexString(0xff & byteData[i]); | |
if(hex.length()==1) | |
{ | |
hexString.append('0'); | |
} | |
hexString.append(hex); | |
} | |
result = hexString.toString(); | |
} | |
catch (NoSuchAlgorithmException e) | |
{ | |
e.printStackTrace(); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment