Home | History | Annotate | Download | only in asn1
      1 package org.bouncycastle.asn1;
      2 
      3 import java.io.FilterOutputStream;
      4 import java.io.IOException;
      5 import java.io.OutputStream;
      6 
      7 public class DEROutputStream
      8     extends FilterOutputStream implements DERTags
      9 {
     10     public DEROutputStream(
     11         OutputStream    os)
     12     {
     13         super(os);
     14     }
     15 
     16     private void writeLength(
     17         int length)
     18         throws IOException
     19     {
     20         if (length > 127)
     21         {
     22             int size = 1;
     23             int val = length;
     24 
     25             while ((val >>>= 8) != 0)
     26             {
     27                 size++;
     28             }
     29 
     30             write((byte)(size | 0x80));
     31 
     32             for (int i = (size - 1) * 8; i >= 0; i -= 8)
     33             {
     34                 write((byte)(length >> i));
     35             }
     36         }
     37         else
     38         {
     39             write((byte)length);
     40         }
     41     }
     42 
     43     void writeEncoded(
     44         int     tag,
     45         byte[]  bytes)
     46         throws IOException
     47     {
     48         write(tag);
     49         writeLength(bytes.length);
     50         write(bytes);
     51     }
     52 
     53     protected void writeNull()
     54         throws IOException
     55     {
     56         write(NULL);
     57         write(0x00);
     58     }
     59 
     60     public void writeObject(
     61         Object    obj)
     62         throws IOException
     63     {
     64         if (obj == null)
     65         {
     66             writeNull();
     67         }
     68         else if (obj instanceof DERObject)
     69         {
     70             ((DERObject)obj).encode(this);
     71         }
     72         else if (obj instanceof DEREncodable)
     73         {
     74             ((DEREncodable)obj).getDERObject().encode(this);
     75         }
     76         else
     77         {
     78             throw new IOException("object not DEREncodable");
     79         }
     80     }
     81 }
     82