1 package org.bouncycastle.operator;
2 
3 import java.io.IOException;
4 import java.io.OutputStream;
5 
6 import org.bouncycastle.util.Arrays;
7 
8 /**
9  * A generic class for capturing the mac data at the end of a encrypted data stream.
10  * <p>
11  * Note: this class will not close the underlying stream.
12  * </p>
13  */
14 public class MacCaptureStream
15     extends OutputStream
16 {
17     private final OutputStream cOut;
18     private final byte[] mac;
19 
20     int macIndex = 0;
21 
MacCaptureStream(OutputStream cOut, int macLength)22     public MacCaptureStream(OutputStream cOut, int macLength)
23     {
24         this.cOut = cOut;
25         this.mac = new byte[macLength];
26     }
27 
write(byte[] buf, int off, int len)28     public void write(byte[] buf, int off, int len)
29         throws IOException
30     {
31         if (len >= mac.length)
32         {
33             cOut.write(mac, 0, macIndex);
34             macIndex = mac.length;
35             System.arraycopy(buf, off + len - mac.length, mac, 0, mac.length);
36             cOut.write(buf, off, len - mac.length);
37         }
38         else
39         {
40             for (int i = 0; i != len; i++)
41             {
42                 write(buf[off + i]);
43             }
44         }
45     }
46 
write(int b)47     public void write(int b)
48         throws IOException
49     {
50         if (macIndex == mac.length)
51         {
52              byte b1 = mac[0];
53              System.arraycopy(mac, 1, mac, 0, mac.length - 1);
54              mac[mac.length - 1] = (byte)b;
55              cOut.write(b1);
56         }
57         else
58         {
59             mac[macIndex++] = (byte)b;
60         }
61     }
62 
getMac()63     public byte[] getMac()
64     {
65         return Arrays.clone(mac);
66     }
67 }
68