1package org.bouncycastle.asn1; 2 3import java.io.IOException; 4import java.io.OutputStream; 5 6public class BEROctetStringGenerator 7 extends BERGenerator 8{ 9 public BEROctetStringGenerator(OutputStream out) 10 throws IOException 11 { 12 super(out); 13 14 writeBERHeader(BERTags.CONSTRUCTED | BERTags.OCTET_STRING); 15 } 16 17 public BEROctetStringGenerator( 18 OutputStream out, 19 int tagNo, 20 boolean isExplicit) 21 throws IOException 22 { 23 super(out, tagNo, isExplicit); 24 25 writeBERHeader(BERTags.CONSTRUCTED | BERTags.OCTET_STRING); 26 } 27 28 public OutputStream getOctetOutputStream() 29 { 30 return getOctetOutputStream(new byte[1000]); // limit for CER encoding. 31 } 32 33 public OutputStream getOctetOutputStream( 34 byte[] buf) 35 { 36 return new BufferedBEROctetStream(buf); 37 } 38 39 private class BufferedBEROctetStream 40 extends OutputStream 41 { 42 private byte[] _buf; 43 private int _off; 44 private DEROutputStream _derOut; 45 46 BufferedBEROctetStream( 47 byte[] buf) 48 { 49 _buf = buf; 50 _off = 0; 51 _derOut = new DEROutputStream(_out); 52 } 53 54 public void write( 55 int b) 56 throws IOException 57 { 58 _buf[_off++] = (byte)b; 59 60 if (_off == _buf.length) 61 { 62 DEROctetString.encode(_derOut, _buf); 63 _off = 0; 64 } 65 } 66 67 public void write(byte[] b, int off, int len) throws IOException 68 { 69 while (len > 0) 70 { 71 int numToCopy = Math.min(len, _buf.length - _off); 72 System.arraycopy(b, off, _buf, _off, numToCopy); 73 74 _off += numToCopy; 75 if (_off < _buf.length) 76 { 77 break; 78 } 79 80 DEROctetString.encode(_derOut, _buf); 81 _off = 0; 82 83 off += numToCopy; 84 len -= numToCopy; 85 } 86 } 87 88 public void close() 89 throws IOException 90 { 91 if (_off != 0) 92 { 93 byte[] bytes = new byte[_off]; 94 System.arraycopy(_buf, 0, bytes, 0, _off); 95 96 DEROctetString.encode(_derOut, bytes); 97 } 98 99 writeBEREnd(); 100 } 101 } 102} 103