01: package org.bouncycastle.crypto.tls;
02:
03: import java.io.IOException;
04: import java.io.InputStream;
05: import java.io.OutputStream;
06:
07: /**
08: * An implementation of the TLS 1.0 record layer.
09: */
10: public class RecordStream {
11:
12: private TlsProtocolHandler handler;
13: private InputStream is;
14: private OutputStream os;
15: protected CombinedHash hash1;
16: protected CombinedHash hash2;
17: protected TlsCipherSuite readSuite = null;
18: protected TlsCipherSuite writeSuite = null;
19:
20: protected RecordStream(TlsProtocolHandler handler, InputStream is,
21: OutputStream os) {
22: this .handler = handler;
23: this .is = is;
24: this .os = os;
25: hash1 = new CombinedHash();
26: hash2 = new CombinedHash();
27: this .readSuite = new TlsNullCipherSuite();
28: this .writeSuite = this .readSuite;
29: }
30:
31: public void readData() throws IOException {
32: short type = TlsUtils.readUint8(is);
33: TlsUtils.checkVersion(is, handler);
34: int size = TlsUtils.readUint16(is);
35: byte[] buf = decodeAndVerify(type, is, size);
36: handler.processData(type, buf, 0, buf.length);
37:
38: }
39:
40: protected byte[] decodeAndVerify(short type, InputStream is, int len)
41: throws IOException {
42: byte[] buf = new byte[len];
43: TlsUtils.readFully(buf, is);
44: byte[] result = readSuite.decodeCiphertext(type, buf, 0,
45: buf.length, handler);
46: return result;
47: }
48:
49: protected void writeMessage(short type, byte[] message, int offset,
50: int len) throws IOException {
51: if (type == 22) {
52: hash1.update(message, offset, len);
53: hash2.update(message, offset, len);
54: }
55: byte[] ciphertext = writeSuite.encodePlaintext(type, message,
56: offset, len);
57: byte[] writeMessage = new byte[ciphertext.length + 5];
58: TlsUtils.writeUint8(type, writeMessage, 0);
59: TlsUtils.writeUint8((short) 3, writeMessage, 1);
60: TlsUtils.writeUint8((short) 1, writeMessage, 2);
61: TlsUtils.writeUint16(ciphertext.length, writeMessage, 3);
62: System.arraycopy(ciphertext, 0, writeMessage, 5,
63: ciphertext.length);
64: os.write(writeMessage);
65: os.flush();
66: }
67:
68: protected void close() throws IOException {
69: IOException e = null;
70: try {
71: is.close();
72: } catch (IOException ex) {
73: e = ex;
74: }
75: try {
76: os.close();
77: } catch (IOException ex) {
78: e = ex;
79: }
80: if (e != null) {
81: throw e;
82: }
83: }
84:
85: protected void flush() throws IOException {
86: os.flush();
87: }
88:
89: }
|