1 | /**************************************************************** |
2 | * Licensed to the Apache Software Foundation (ASF) under one * |
3 | * or more contributor license agreements. See the NOTICE file * |
4 | * distributed with this work for additional information * |
5 | * regarding copyright ownership. The ASF licenses this file * |
6 | * to you under the Apache License, Version 2.0 (the * |
7 | * "License"); you may not use this file except in compliance * |
8 | * with the License. You may obtain a copy of the License at * |
9 | * * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 * |
11 | * * |
12 | * Unless required by applicable law or agreed to in writing, * |
13 | * software distributed under the License is distributed on an * |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * |
15 | * KIND, either express or implied. See the License for the * |
16 | * specific language governing permissions and limitations * |
17 | * under the License. * |
18 | ****************************************************************/ |
19 | |
20 | package org.apache.james.jdkim.canon; |
21 | |
22 | import java.io.FilterOutputStream; |
23 | import java.io.IOException; |
24 | import java.io.OutputStream; |
25 | import java.security.MessageDigest; |
26 | |
27 | /** |
28 | * DigestOutputStream is used as a filter stream or as the ending stream in |
29 | * order to calculate a digest of a stream. |
30 | */ |
31 | public class DigestOutputStream extends FilterOutputStream { |
32 | |
33 | private MessageDigest md; |
34 | |
35 | public DigestOutputStream(MessageDigest md) { |
36 | this(md, null); |
37 | } |
38 | |
39 | public DigestOutputStream(MessageDigest md, OutputStream out) { |
40 | super(out); |
41 | this.md = md; |
42 | } |
43 | |
44 | public void write(int arg0) throws IOException { |
45 | md.update((byte) arg0); |
46 | if (out != null) |
47 | out.write(arg0); |
48 | } |
49 | |
50 | public void write(byte[] b, int off, int len) throws IOException { |
51 | md.update(b, off, len); |
52 | if (out != null) |
53 | out.write(b, off, len); |
54 | } |
55 | |
56 | public void close() throws IOException { |
57 | if (out != null) |
58 | super.close(); |
59 | } |
60 | |
61 | public void flush() throws IOException { |
62 | if (out != null) |
63 | super.flush(); |
64 | } |
65 | |
66 | public void write(byte[] b) throws IOException { |
67 | md.update(b); |
68 | if (out != null) |
69 | out.write(b); |
70 | } |
71 | |
72 | /** |
73 | * @return the stream digest as a byte array |
74 | */ |
75 | public byte[] getDigest() { |
76 | return md.digest(); |
77 | } |
78 | |
79 | } |