Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.libg.cryptography; |
| 2 | |
| 3 | import java.util.*; |
| 4 | |
| 5 | import aQute.lib.hex.*; |
| 6 | |
| 7 | public abstract class Digest { |
| 8 | final byte[] digest; |
| 9 | |
| 10 | protected Digest(byte[] checksum, int width) { |
| 11 | this.digest = checksum; |
| 12 | if (digest.length != width) |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 13 | throw new IllegalArgumentException("Invalid width for digest: " + digest.length + " expected " + width); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 14 | } |
| 15 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 16 | public byte[] digest() { |
| 17 | return digest; |
| 18 | } |
| 19 | |
Stuart McCulloch | 39cc9ac | 2012-07-16 13:43:38 +0000 | [diff] [blame^] | 20 | public String asHex() { |
| 21 | return Hex.toHexString(digest()); |
| 22 | } |
| 23 | |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 24 | @Override |
| 25 | public String toString() { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 26 | return String.format("%s(d=%s)", getAlgorithm(), Hex.toHexString(digest)); |
| 27 | } |
| 28 | |
| 29 | public abstract String getAlgorithm(); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 30 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 31 | public boolean equals(Object other) { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 32 | if (!(other instanceof Digest)) |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 33 | return false; |
| 34 | |
| 35 | Digest d = (Digest) other; |
| 36 | return Arrays.equals(d.digest, digest); |
| 37 | } |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 38 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 39 | public int hashCode() { |
| 40 | return Arrays.hashCode(digest); |
| 41 | } |
| 42 | |
| 43 | public byte[] toByteArray() { |
| 44 | return digest(); |
| 45 | } |
| 46 | } |