blob: 119a35b3842907092b110387c62d0304e273f860 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.libg.cryptography;
2
3import java.util.*;
4
5import aQute.lib.hex.*;
6
7public 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 McCulloch2286f232012-06-15 13:27:53 +000013 throw new IllegalArgumentException("Invalid width for digest: " + digest.length + " expected " + width);
Stuart McCullochbb014372012-06-07 21:57:32 +000014 }
15
Stuart McCullochbb014372012-06-07 21:57:32 +000016 public byte[] digest() {
17 return digest;
18 }
19
Stuart McCulloch39cc9ac2012-07-16 13:43:38 +000020 public String asHex() {
21 return Hex.toHexString(digest());
22 }
23
Stuart McCulloch2286f232012-06-15 13:27:53 +000024 @Override
25 public String toString() {
Stuart McCullochbb014372012-06-07 21:57:32 +000026 return String.format("%s(d=%s)", getAlgorithm(), Hex.toHexString(digest));
27 }
28
29 public abstract String getAlgorithm();
Stuart McCulloch2286f232012-06-15 13:27:53 +000030
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000031 @Override
Stuart McCullochbb014372012-06-07 21:57:32 +000032 public boolean equals(Object other) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000033 if (!(other instanceof Digest))
Stuart McCullochbb014372012-06-07 21:57:32 +000034 return false;
35
36 Digest d = (Digest) other;
37 return Arrays.equals(d.digest, digest);
38 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000039
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000040 @Override
Stuart McCullochbb014372012-06-07 21:57:32 +000041 public int hashCode() {
42 return Arrays.hashCode(digest);
43 }
44
45 public byte[] toByteArray() {
46 return digest();
47 }
48}