Created
July 26, 2019 21:08
-
-
Save tolgasumer/32ed8d2f24beb9cb48cf6baa8c86351f to your computer and use it in GitHub Desktop.
MD5 encryption Java class
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.security.MessageDigest; | |
public class MD5 | |
{ | |
static byte[] digest; | |
public MD5() { | |
} | |
public static String getHash(String stringToHash) | |
{ | |
// hexString is used to store the hash | |
StringBuffer hexString = new StringBuffer(); | |
// Get a byte array of the String to be hashed | |
byte[] buffer = stringToHash.getBytes(); | |
try | |
{ | |
// Get and instance of the MD5 MessageDigest | |
MessageDigest alg = MessageDigest.getInstance("MD5"); | |
// Make sure the Digest is clear | |
alg.reset(); | |
// Populate the Digest with the byte array | |
alg.update(buffer); | |
// Create the MD5 Hash | |
digest = alg.digest(); | |
// Now we need to pull out each char of the byte array into the StringBuffer | |
} | |
catch(Exception e) | |
{ | |
// Need to catch some exceptions | |
} | |
// Return the hex hash value as a String | |
return asHex(digest); | |
} | |
private static String asHex (byte hash[]) { | |
StringBuffer buf = new StringBuffer(hash.length * 2); | |
int i; | |
for (i = 0; i < hash.length; i++) { | |
if (((int) hash[i] & 0xff) < 0x10) | |
buf.append("0"); | |
buf.append(Long.toString((int) hash[i] & 0xff, 16)); | |
} | |
return buf.toString(); | |
} | |
} | |
// Usage: String hash = MD5.getHash("somepassword"); | |
// INSERT INTO table VALUES (MD5('yourstring')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment