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