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