blob: 2722ab1aadd3d13a72ccefd5fed8eb1144580b86 [file] [log] [blame]
Stuart McCullochf3173222012-06-07 21:57:32 +00001package aQute.libg.cryptography;
2
3import java.io.*;
4import java.security.*;
5
6import aQute.lib.io.*;
7
8public abstract class Digester<T extends Digest> extends OutputStream {
9 protected MessageDigest md;
Stuart McCulloch4482c702012-06-15 13:27:53 +000010 OutputStream out[];
11
12 public Digester(MessageDigest instance, OutputStream... out) {
Stuart McCullochf3173222012-06-07 21:57:32 +000013 md = instance;
14 this.out = out;
15 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000016
Stuart McCullochf3173222012-06-07 21:57:32 +000017 @Override
Stuart McCulloch4482c702012-06-15 13:27:53 +000018 public void write(byte[] buffer, int offset, int length) throws IOException {
19 md.update(buffer, offset, length);
20 for (OutputStream o : out) {
Stuart McCullochf3173222012-06-07 21:57:32 +000021 o.write(buffer, offset, length);
22 }
23 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000024
Stuart McCullochf3173222012-06-07 21:57:32 +000025 @Override
Stuart McCulloch4482c702012-06-15 13:27:53 +000026 public void write(int b) throws IOException {
Stuart McCullochf3173222012-06-07 21:57:32 +000027 md.update((byte) b);
Stuart McCulloch4482c702012-06-15 13:27:53 +000028 for (OutputStream o : out) {
Stuart McCullochf3173222012-06-07 21:57:32 +000029 o.write(b);
30 }
31 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000032
Stuart McCullochf3173222012-06-07 21:57:32 +000033 public MessageDigest getMessageDigest() throws Exception {
34 return md;
35 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000036
Stuart McCullochf3173222012-06-07 21:57:32 +000037 public T from(InputStream in) throws Exception {
Stuart McCulloch4482c702012-06-15 13:27:53 +000038 IO.copy(in, this);
Stuart McCullochf3173222012-06-07 21:57:32 +000039 return digest();
40 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000041
42 public void setOutputs(OutputStream... out) {
Stuart McCullochf3173222012-06-07 21:57:32 +000043 this.out = out;
44 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000045
Stuart McCullochf3173222012-06-07 21:57:32 +000046 public abstract T digest() throws Exception;
Stuart McCulloch4482c702012-06-15 13:27:53 +000047
48 public abstract T digest(byte[] bytes) throws Exception;
49
Stuart McCullochf3173222012-06-07 21:57:32 +000050 public abstract String getAlgorithm();
Stuart McCulloch2a0afd62012-09-06 18:28:06 +000051
52 public T from(File f) throws Exception {
53 IO.copy(f, this);
54 return digest();
55 }
56 public T from(byte[] f) throws Exception {
57 IO.copy(f, this);
58 return digest();
59 }
Stuart McCullochf3173222012-06-07 21:57:32 +000060}