01: package org.bouncycastle.asn1;
02:
03: import java.io.IOException;
04: import java.io.OutputStream;
05:
06: public class BEROctetStringGenerator extends BERGenerator {
07: public BEROctetStringGenerator(OutputStream out) throws IOException {
08: super (out);
09:
10: writeBERHeader(DERTags.CONSTRUCTED | DERTags.OCTET_STRING);
11: }
12:
13: public BEROctetStringGenerator(OutputStream out, int tagNo,
14: boolean isExplicit) throws IOException {
15: super (out, tagNo, isExplicit);
16:
17: writeBERHeader(DERTags.CONSTRUCTED | DERTags.OCTET_STRING);
18: }
19:
20: public OutputStream getOctetOutputStream() {
21: return getOctetOutputStream(new byte[1000]); // limit for CER encoding.
22: }
23:
24: public OutputStream getOctetOutputStream(byte[] buf) {
25: return new BufferedBEROctetStream(buf);
26: }
27:
28: private class BufferedBEROctetStream extends OutputStream {
29: private byte[] _buf;
30: private int _off;
31:
32: BufferedBEROctetStream(byte[] buf) {
33: _buf = buf;
34: _off = 0;
35: }
36:
37: public void write(int b) throws IOException {
38: _buf[_off++] = (byte) b;
39:
40: if (_off == _buf.length) {
41: _out.write(new DEROctetString(_buf).getEncoded());
42: _off = 0;
43: }
44: }
45:
46: public void write(byte[] b, int off, int len)
47: throws IOException {
48: while (len > 0) {
49: int numToCopy = Math.min(len, _buf.length - _off);
50: System.arraycopy(b, off, _buf, _off, numToCopy);
51:
52: _off += numToCopy;
53: if (_off < _buf.length) {
54: break;
55: }
56:
57: _out.write(new DEROctetString(_buf).getEncoded());
58: _off = 0;
59:
60: off += numToCopy;
61: len -= numToCopy;
62: }
63: }
64:
65: public void close() throws IOException {
66: if (_off != 0) {
67: byte[] bytes = new byte[_off];
68: System.arraycopy(_buf, 0, bytes, 0, _off);
69:
70: _out.write(new DEROctetString(bytes).getEncoded());
71: }
72:
73: writeBEREnd();
74: }
75: }
76: }
|