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