Created
September 21, 2016 04:09
-
-
Save oguna/4b5670d259cc05fc7e787875dabfce98 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
| import java.security.NoSuchAlgorithmException; | |
| import java.util.Arrays; | |
| public class Md5Hash { | |
| private final byte[] digest; | |
| private final int hashCode; | |
| private Md5Hash(byte[] digest) { | |
| if (digest == null || digest.length != 16) { | |
| throw new IllegalArgumentException(); | |
| } | |
| this.hashCode = Arrays.hashCode(digest); | |
| this.digest = digest; | |
| } | |
| public static Md5Hash fromByteArray(byte[] array) { | |
| if (array == null) { | |
| throw new IllegalArgumentException(); | |
| } | |
| MessageDigest messageDigest = getMd5Digest(); | |
| messageDigest.update(array); | |
| return new Md5Hash(messageDigest.digest()); | |
| } | |
| public static Md5Hash fromString(String string) { | |
| if (string == null) { | |
| throw new IllegalArgumentException(); | |
| } | |
| MessageDigest messageDigest = getMd5Digest(); | |
| messageDigest.update(string.getBytes()); | |
| return new Md5Hash(messageDigest.digest()); | |
| } | |
| public static Md5Hash fromDigest(byte[] digest) { | |
| return new Md5Hash(digest); | |
| } | |
| public byte[] getDigest() { | |
| return Arrays.copyOf(digest, digest.length); | |
| } | |
| @Override | |
| public int hashCode() { | |
| return hashCode; | |
| } | |
| @Override | |
| public boolean equals(Object o) { | |
| if (this == o) return true; | |
| if (o == null || getClass() != o.getClass()) return false; | |
| Md5Hash hash = (Md5Hash) o; | |
| return hashCode == hash.hashCode && | |
| Arrays.equals(digest, hash.digest); | |
| } | |
| private static MessageDigest getMd5Digest() { | |
| try { | |
| return MessageDigest.getInstance("MD5"); | |
| } catch (NoSuchAlgorithmException e) { | |
| throw new RuntimeException(e); | |
| } | |
| } | |
| @Override | |
| public String toString() { | |
| StringBuilder sb = new StringBuilder(32); | |
| for (int i = 0; i < digest.length; i++) { | |
| if (digest[i] > 9) { | |
| sb.append('0'); | |
| } | |
| sb.append(Integer.toUnsignedString(digest[i], 16)); | |
| } | |
| return sb.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment