blob: aeb4bbb89a4e0d5769aa8816f56432e3293417d8 [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 McCullochbb014372012-06-07 21:57:32 +000031 public boolean equals(Object other) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000032 if (!(other instanceof Digest))
Stuart McCullochbb014372012-06-07 21:57:32 +000033 return false;
34
35 Digest d = (Digest) other;
36 return Arrays.equals(d.digest, digest);
37 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000038
Stuart McCullochbb014372012-06-07 21:57:32 +000039 public int hashCode() {
40 return Arrays.hashCode(digest);
41 }
42
43 public byte[] toByteArray() {
44 return digest();
45 }
46}