1package org.bouncycastle.operator.bc;
2
3import java.io.IOException;
4import java.io.OutputStream;
5import java.util.Map;
6
7import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
8import org.bouncycastle.crypto.Digest;
9import org.bouncycastle.crypto.ExtendedDigest;
10import org.bouncycastle.operator.DigestCalculator;
11import org.bouncycastle.operator.DigestCalculatorProvider;
12import org.bouncycastle.operator.OperatorCreationException;
13
14public class BcDigestCalculatorProvider
15    implements DigestCalculatorProvider
16{
17    private BcDigestProvider digestProvider = BcDefaultDigestProvider.INSTANCE;
18
19    public DigestCalculator get(final AlgorithmIdentifier algorithm)
20        throws OperatorCreationException
21    {
22        Digest dig = digestProvider.get(algorithm);
23
24        final DigestOutputStream stream = new DigestOutputStream(dig);
25
26        return new DigestCalculator()
27        {
28            public AlgorithmIdentifier getAlgorithmIdentifier()
29            {
30                return algorithm;
31            }
32
33            public OutputStream getOutputStream()
34            {
35                return stream;
36            }
37
38            public byte[] getDigest()
39            {
40                return stream.getDigest();
41            }
42        };
43    }
44
45    private class DigestOutputStream
46        extends OutputStream
47    {
48        private Digest dig;
49
50        DigestOutputStream(Digest dig)
51        {
52            this.dig = dig;
53        }
54
55        public void write(byte[] bytes, int off, int len)
56            throws IOException
57        {
58            dig.update(bytes, off, len);
59        }
60
61        public void write(byte[] bytes)
62            throws IOException
63        {
64            dig.update(bytes, 0, bytes.length);
65        }
66
67        public void write(int b)
68            throws IOException
69        {
70            dig.update((byte)b);
71        }
72
73        byte[] getDigest()
74        {
75            byte[] d = new byte[dig.getDigestSize()];
76
77            dig.doFinal(d, 0);
78
79            return d;
80        }
81    }
82}