KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > maverick > crypto > asn1 > DEROutputStream


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.maverick.crypto.asn1;
21
22 import java.io.FilterOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.OutputStream JavaDoc;
25
26 public class DEROutputStream
27     extends FilterOutputStream JavaDoc implements DERTags
28 {
29     public DEROutputStream(
30         OutputStream JavaDoc os)
31     {
32         super(os);
33     }
34
35     private void writeLength(
36         int length)
37         throws IOException JavaDoc
38     {
39         if (length > 127)
40         {
41             int size = 1;
42             int val = length;
43
44             while ((val >>>= 8) != 0)
45             {
46                 size++;
47             }
48
49             write((byte)(size | 0x80));
50
51             for (int i = (size - 1) * 8; i >= 0; i -= 8)
52             {
53                 write((byte)(length >> i));
54             }
55         }
56         else
57         {
58             write((byte)length);
59         }
60     }
61
62     void writeEncoded(
63         int tag,
64         byte[] bytes)
65         throws IOException JavaDoc
66     {
67         write(tag);
68         writeLength(bytes.length);
69         write(bytes);
70     }
71
72     protected void writeNull()
73         throws IOException JavaDoc
74     {
75         write(NULL);
76         write(0x00);
77     }
78
79     public void writeObject(
80         Object JavaDoc obj)
81         throws IOException JavaDoc
82     {
83         if (obj == null)
84         {
85             writeNull();
86         }
87         else if (obj instanceof DERObject)
88         {
89             ((DERObject)obj).encode(this);
90         }
91         else if (obj instanceof DEREncodable)
92         {
93             ((DEREncodable)obj).getDERObject().encode(this);
94         }
95         else
96         {
97             throw new IOException JavaDoc("object not DEREncodable");
98         }
99     }
100 }
101
Popular Tags