blob: 93d48adf5e2c3817d1c2bb8b66122e36f14983e8 [file] [log] [blame]
Stuart McCullochf3173222012-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 McCulloch4482c702012-06-15 13:27:53 +000013 throw new IllegalArgumentException("Invalid width for digest: " + digest.length + " expected " + width);
Stuart McCullochf3173222012-06-07 21:57:32 +000014 }
15
Stuart McCullochf3173222012-06-07 21:57:32 +000016 public byte[] digest() {
17 return digest;
18 }
19
Stuart McCulloch4482c702012-06-15 13:27:53 +000020 @Override
21 public String toString() {
Stuart McCullochf3173222012-06-07 21:57:32 +000022 return String.format("%s(d=%s)", getAlgorithm(), Hex.toHexString(digest));
23 }
24
25 public abstract String getAlgorithm();
Stuart McCulloch4482c702012-06-15 13:27:53 +000026
Stuart McCullochf3173222012-06-07 21:57:32 +000027 public boolean equals(Object other) {
Stuart McCulloch4482c702012-06-15 13:27:53 +000028 if (!(other instanceof Digest))
Stuart McCullochf3173222012-06-07 21:57:32 +000029 return false;
30
31 Digest d = (Digest) other;
32 return Arrays.equals(d.digest, digest);
33 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000034
Stuart McCullochf3173222012-06-07 21:57:32 +000035 public int hashCode() {
36 return Arrays.hashCode(digest);
37 }
38
39 public byte[] toByteArray() {
40 return digest();
41 }
42}