001package org.apache.commons.ssl.asn1;
002
003import java.io.IOException;
004import java.io.InputStream;
005import java.io.OutputStream;
006
007public class BERGenerator
008    extends ASN1Generator {
009    private boolean _tagged = false;
010    private boolean _isExplicit;
011    private int _tagNo;
012
013    protected BERGenerator(
014        OutputStream out) {
015        super(out);
016    }
017
018    public BERGenerator(
019        OutputStream out,
020        int tagNo,
021        boolean isExplicit) {
022        super(out);
023
024        _tagged = true;
025        _isExplicit = isExplicit;
026        _tagNo = tagNo;
027    }
028
029    public OutputStream getRawOutputStream() {
030        return _out;
031    }
032
033    private void writeHdr(
034        int tag)
035        throws IOException {
036        _out.write(tag);
037        _out.write(0x80);
038    }
039
040    protected void writeBERHeader(
041        int tag)
042        throws IOException {
043        if (_tagged) {
044            int tagNum = _tagNo | DERTags.TAGGED;
045
046            if (_isExplicit) {
047                writeHdr(tagNum | DERTags.CONSTRUCTED);
048                writeHdr(tag);
049            } else {
050                if ((tag & DERTags.CONSTRUCTED) != 0) {
051                    writeHdr(tagNum | DERTags.CONSTRUCTED);
052                } else {
053                    writeHdr(tagNum);
054                }
055            }
056        } else {
057            writeHdr(tag);
058        }
059    }
060
061    protected void writeBERBody(
062        InputStream contentStream)
063        throws IOException {
064        int ch;
065
066        while ((ch = contentStream.read()) >= 0) {
067            _out.write(ch);
068        }
069    }
070
071    protected void writeBEREnd()
072        throws IOException {
073        _out.write(0x00);
074        _out.write(0x00);
075
076        if (_tagged && _isExplicit)  // write extra end for tag header
077        {
078            _out.write(0x00);
079            _out.write(0x00);
080        }
081    }
082}