1 package ch.ethz.ssh2.crypto; 2 3 import java.io.IOException ; 4 5 import java.math.BigInteger ; 6 7 13 public class SimpleDERReader 14 { 15 byte[] buffer; 16 int pos; 17 int count; 18 19 public SimpleDERReader(byte[] b) 20 { 21 resetInput(b); 22 } 23 24 public SimpleDERReader(byte[] b, int off, int len) 25 { 26 resetInput(b, off, len); 27 } 28 29 public void resetInput(byte[] b) 30 { 31 resetInput(b, 0, b.length); 32 } 33 34 public void resetInput(byte[] b, int off, int len) 35 { 36 buffer = b; 37 pos = off; 38 count = len; 39 } 40 41 private byte readByte() throws IOException 42 { 43 if (count <= 0) 44 throw new IOException ("DER byte array: out of data"); 45 count--; 46 return buffer[pos++]; 47 } 48 49 private byte[] readBytes(int len) throws IOException 50 { 51 if (len > count) 52 throw new IOException ("DER byte array: out of data"); 53 54 byte[] b = new byte[len]; 55 56 System.arraycopy(buffer, pos, b, 0, len); 57 58 pos += len; 59 count -= len; 60 61 return b; 62 } 63 64 public int available() 65 { 66 return count; 67 } 68 69 private int readLength() throws IOException 70 { 71 int len = readByte() & 0xff; 72 73 if ((len & 0x80) == 0) 74 return len; 75 76 int remain = len & 0x7F; 77 78 if (remain == 0) 79 return -1; 80 81 len = 0; 82 83 while (remain > 0) 84 { 85 len = len << 8; 86 len = len | (readByte() & 0xff); 87 remain--; 88 } 89 90 return len; 91 } 92 93 public int ignoreNextObject() throws IOException 94 { 95 int type = readByte() & 0xff; 96 97 int len = readLength(); 98 99 if ((len < 0) || len > available()) 100 throw new IOException ("Illegal len in DER object (" + len + ")"); 101 102 readBytes(len); 103 104 return type; 105 } 106 107 public BigInteger readInt() throws IOException 108 { 109 int type = readByte() & 0xff; 110 111 if (type != 0x02) 112 throw new IOException ("Expected DER Integer, but found type " + type); 113 114 int len = readLength(); 115 116 if ((len < 0) || len > available()) 117 throw new IOException ("Illegal len in DER object (" + len + ")"); 118 119 byte[] b = readBytes(len); 120 121 BigInteger bi = new BigInteger (b); 122 123 return bi; 124 } 125 126 public byte[] readSequenceAsByteArray() throws IOException 127 { 128 int type = readByte() & 0xff; 129 130 if (type != 0x30) 131 throw new IOException ("Expected DER Sequence, but found type " + type); 132 133 int len = readLength(); 134 135 if ((len < 0) || len > available()) 136 throw new IOException ("Illegal len in DER object (" + len + ")"); 137 138 byte[] b = readBytes(len); 139 140 return b; 141 } 142 143 public byte[] readOctetString() throws IOException 144 { 145 int type = readByte() & 0xff; 146 147 if (type != 0x04) 148 throw new IOException ("Expected DER Octetstring, but found type " + type); 149 150 int len = readLength(); 151 152 if ((len < 0) || len > available()) 153 throw new IOException ("Illegal len in DER object (" + len + ")"); 154 155 byte[] b = readBytes(len); 156 157 return b; 158 } 159 160 } 161 | Popular Tags |