273
|
1 /*
|
|
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
|
|
3 * Please refer to the LICENSE.txt for licensing details.
|
|
4 */
|
|
5 package ch.ethz.ssh2.crypto.cipher;
|
|
6
|
|
7 /**
|
|
8 * CBCMode.
|
307
|
9 *
|
273
|
10 * @author Christian Plattner
|
|
11 * @version 2.50, 03/15/10
|
|
12 */
|
307
|
13 public class CBCMode implements BlockCipher {
|
|
14 BlockCipher tc;
|
|
15 int blockSize;
|
|
16 boolean doEncrypt;
|
273
|
17
|
307
|
18 byte[] cbc_vector;
|
|
19 byte[] tmp_vector;
|
|
20
|
|
21 public void init(boolean forEncryption, byte[] key) {
|
|
22 }
|
273
|
23
|
307
|
24 public CBCMode(BlockCipher tc, byte[] iv, boolean doEncrypt)
|
|
25 throws IllegalArgumentException {
|
|
26 this.tc = tc;
|
|
27 this.blockSize = tc.getBlockSize();
|
|
28 this.doEncrypt = doEncrypt;
|
273
|
29
|
307
|
30 if (this.blockSize != iv.length)
|
|
31 throw new IllegalArgumentException("IV must be " + blockSize
|
|
32 + " bytes long! (currently " + iv.length + ")");
|
273
|
33
|
307
|
34 this.cbc_vector = new byte[blockSize];
|
|
35 this.tmp_vector = new byte[blockSize];
|
|
36 System.arraycopy(iv, 0, cbc_vector, 0, blockSize);
|
|
37 }
|
273
|
38
|
307
|
39 public int getBlockSize() {
|
|
40 return blockSize;
|
|
41 }
|
273
|
42
|
307
|
43 private void encryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff) {
|
|
44 for (int i = 0; i < blockSize; i++)
|
|
45 cbc_vector[i] ^= src[srcoff + i];
|
273
|
46
|
307
|
47 tc.transformBlock(cbc_vector, 0, dst, dstoff);
|
|
48 System.arraycopy(dst, dstoff, cbc_vector, 0, blockSize);
|
|
49 }
|
273
|
50
|
307
|
51 private void decryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff) {
|
|
52 /* Assume the worst, src and dst are overlapping... */
|
|
53 System.arraycopy(src, srcoff, tmp_vector, 0, blockSize);
|
|
54 tc.transformBlock(src, srcoff, dst, dstoff);
|
273
|
55
|
307
|
56 for (int i = 0; i < blockSize; i++)
|
|
57 dst[dstoff + i] ^= cbc_vector[i];
|
273
|
58
|
307
|
59 /* ...that is why we need a tmp buffer. */
|
|
60 byte[] swap = cbc_vector;
|
|
61 cbc_vector = tmp_vector;
|
|
62 tmp_vector = swap;
|
|
63 }
|
273
|
64
|
307
|
65 public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff) {
|
|
66 if (doEncrypt)
|
|
67 encryptBlock(src, srcoff, dst, dstoff);
|
|
68 else
|
|
69 decryptBlock(src, srcoff, dst, dstoff);
|
|
70 }
|
273
|
71 }
|