blob: 2785c3d1d477125d9af6a358873490629aa4df26 [file] [log] [blame]
Stuart McCullochbb014372012-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 McCulloch2286f232012-06-15 13:27:53 +000010 OutputStream out[];
11
12 public Digester(MessageDigest instance, OutputStream... out) {
Stuart McCullochbb014372012-06-07 21:57:32 +000013 md = instance;
14 this.out = out;
15 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000016
Stuart McCullochbb014372012-06-07 21:57:32 +000017 @Override
Stuart McCulloch2286f232012-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 McCullochbb014372012-06-07 21:57:32 +000021 o.write(buffer, offset, length);
22 }
23 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000024
Stuart McCullochbb014372012-06-07 21:57:32 +000025 @Override
Stuart McCulloch2286f232012-06-15 13:27:53 +000026 public void write(int b) throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000027 md.update((byte) b);
Stuart McCulloch2286f232012-06-15 13:27:53 +000028 for (OutputStream o : out) {
Stuart McCullochbb014372012-06-07 21:57:32 +000029 o.write(b);
30 }
31 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000032
Stuart McCullochbb014372012-06-07 21:57:32 +000033 public MessageDigest getMessageDigest() throws Exception {
34 return md;
35 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000036
Stuart McCullochbb014372012-06-07 21:57:32 +000037 public T from(InputStream in) throws Exception {
Stuart McCulloch2286f232012-06-15 13:27:53 +000038 IO.copy(in, this);
Stuart McCullochbb014372012-06-07 21:57:32 +000039 return digest();
40 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000041
42 public void setOutputs(OutputStream... out) {
Stuart McCullochbb014372012-06-07 21:57:32 +000043 this.out = out;
44 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000045
Stuart McCullochbb014372012-06-07 21:57:32 +000046 public abstract T digest() throws Exception;
Stuart McCulloch2286f232012-06-15 13:27:53 +000047
48 public abstract T digest(byte[] bytes) throws Exception;
49
Stuart McCullochbb014372012-06-07 21:57:32 +000050 public abstract String getAlgorithm();
51}