View Javadoc

1   /**
2    *
3    *  Licensed to the Apache Software Foundation (ASF) under one or more
4    *  contributor license agreements.  See the NOTICE file distributed with
5    *  this work for additional information regarding copyright ownership.
6    *  The ASF licenses this file to You under the Apache License, Version 2.0
7    *  (the "License"); you may not use this file except in compliance with
8    *  the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing, software
13   *  distributed under the License is distributed on an "AS IS" BASIS,
14   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   *  See the License for the specific language governing permissions and
16   *  limitations under the License.
17   */
18  
19  package org.apache.geronimo.util.asn1;
20  
21  import java.io.FilterOutputStream;
22  import java.io.IOException;
23  import java.io.OutputStream;
24  
25  public class DEROutputStream
26      extends FilterOutputStream implements DERTags
27  {
28      public DEROutputStream(
29          OutputStream    os)
30      {
31          super(os);
32      }
33  
34      private void writeLength(
35          int length)
36          throws IOException
37      {
38          if (length > 127)
39          {
40              int size = 1;
41              int val = length;
42  
43              while ((val >>>= 8) != 0)
44              {
45                  size++;
46              }
47  
48              write((byte)(size | 0x80));
49  
50              for (int i = (size - 1) * 8; i >= 0; i -= 8)
51              {
52                  write((byte)(length >> i));
53              }
54          }
55          else
56          {
57              write((byte)length);
58          }
59      }
60  
61      void writeEncoded(
62          int     tag,
63          byte[]  bytes)
64          throws IOException
65      {
66          write(tag);
67          writeLength(bytes.length);
68          write(bytes);
69      }
70  
71      protected void writeNull()
72          throws IOException
73      {
74          write(NULL);
75          write(0x00);
76      }
77  
78      public void writeObject(
79          Object    obj)
80          throws IOException
81      {
82          if (obj == null)
83          {
84              writeNull();
85          }
86          else if (obj instanceof DERObject)
87          {
88              ((DERObject)obj).encode(this);
89          }
90          else if (obj instanceof DEREncodable)
91          {
92              ((DEREncodable)obj).getDERObject().encode(this);
93          }
94          else
95          {
96              throw new IOException("object not DEREncodable");
97          }
98      }
99  }