001 package org.apache.commons.ssl.asn1;
002
003 import java.io.FilterOutputStream;
004 import java.io.IOException;
005 import java.io.OutputStream;
006
007 public class DEROutputStream
008 extends FilterOutputStream implements DERTags {
009 public DEROutputStream(
010 OutputStream os) {
011 super(os);
012 }
013
014 private void writeLength(
015 int length)
016 throws IOException {
017 if (length > 127) {
018 int size = 1;
019 int val = length;
020
021 while ((val >>>= 8) != 0) {
022 size++;
023 }
024
025 write((byte) (size | 0x80));
026
027 for (int i = (size - 1) * 8; i >= 0; i -= 8) {
028 write((byte) (length >> i));
029 }
030 } else {
031 write((byte) length);
032 }
033 }
034
035 void writeEncoded(
036 int tag,
037 byte[] bytes)
038 throws IOException {
039 write(tag);
040 writeLength(bytes.length);
041 write(bytes);
042 }
043
044 protected void writeNull()
045 throws IOException {
046 write(NULL);
047 write(0x00);
048 }
049
050 public void write(byte[] buf)
051 throws IOException {
052 out.write(buf, 0, buf.length);
053 }
054
055 public void write(byte[] buf, int offSet, int len)
056 throws IOException {
057 out.write(buf, offSet, len);
058 }
059
060 public void writeObject(
061 Object obj)
062 throws IOException {
063 if (obj == null) {
064 writeNull();
065 } else if (obj instanceof DERObject) {
066 ((DERObject) obj).encode(this);
067 } else if (obj instanceof DEREncodable) {
068 ((DEREncodable) obj).getDERObject().encode(this);
069 } else {
070 throw new IOException("object not DEREncodable");
071 }
072 }
073 }