01: package org.bouncycastle.asn1;
02:
03: import java.io.ByteArrayOutputStream;
04: import java.io.IOException;
05: import java.io.InputStream;
06: import java.io.OutputStream;
07:
08: public abstract class DERGenerator extends ASN1Generator {
09: private boolean _tagged = false;
10: private boolean _isExplicit;
11: private int _tagNo;
12:
13: protected DERGenerator(OutputStream out) {
14: super (out);
15: }
16:
17: public DERGenerator(OutputStream out, int tagNo, boolean isExplicit) {
18: super (out);
19:
20: _tagged = true;
21: _isExplicit = isExplicit;
22: _tagNo = tagNo;
23: }
24:
25: private void writeLength(OutputStream out, int length)
26: throws IOException {
27: if (length > 127) {
28: int size = 1;
29: int val = length;
30:
31: while ((val >>>= 8) != 0) {
32: size++;
33: }
34:
35: out.write((byte) (size | 0x80));
36:
37: for (int i = (size - 1) * 8; i >= 0; i -= 8) {
38: out.write((byte) (length >> i));
39: }
40: } else {
41: out.write((byte) length);
42: }
43: }
44:
45: void writeDEREncoded(OutputStream out, int tag, byte[] bytes)
46: throws IOException {
47: out.write(tag);
48: writeLength(out, bytes.length);
49: out.write(bytes);
50: }
51:
52: void writeDEREncoded(int tag, byte[] bytes) throws IOException {
53: if (_tagged) {
54: int tagNum = _tagNo | DERTags.TAGGED;
55:
56: if (_isExplicit) {
57: int newTag = _tagNo | DERTags.CONSTRUCTED
58: | DERTags.TAGGED;
59:
60: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
61:
62: writeDEREncoded(bOut, tag, bytes);
63:
64: writeDEREncoded(_out, newTag, bOut.toByteArray());
65: } else {
66: if ((tag & DERTags.CONSTRUCTED) != 0) {
67: writeDEREncoded(_out, tagNum | DERTags.CONSTRUCTED,
68: bytes);
69: } else {
70: writeDEREncoded(_out, tagNum, bytes);
71: }
72: }
73: } else {
74: writeDEREncoded(_out, tag, bytes);
75: }
76: }
77:
78: void writeDEREncoded(OutputStream out, int tag, InputStream in)
79: throws IOException {
80: out.write(tag);
81:
82: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
83:
84: int b = 0;
85: while ((b = in.read()) >= 0) {
86: bOut.write(b);
87: }
88:
89: byte[] bytes = bOut.toByteArray();
90:
91: writeLength(out, bytes.length);
92: out.write(bytes);
93: }
94: }
|