comparison app/src/main/java/ch/ethz/ssh2/crypto/cipher/CBCMode.java @ 438:d29cce60f393

migrate from Eclipse to Android Studio
author Carl Byington <carl@five-ten-sg.com>
date Thu, 03 Dec 2015 11:23:55 -0800
parents src/ch/ethz/ssh2/crypto/cipher/CBCMode.java@071eccdff8ea
children
comparison
equal deleted inserted replaced
437:208b31032318 438:d29cce60f393
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.
9 *
10 * @author Christian Plattner
11 * @version 2.50, 03/15/10
12 */
13 public class CBCMode implements BlockCipher {
14 BlockCipher tc;
15 int blockSize;
16 boolean doEncrypt;
17
18 byte[] cbc_vector;
19 byte[] tmp_vector;
20
21 public void init(boolean forEncryption, byte[] key) {
22 }
23
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;
29
30 if (this.blockSize != iv.length)
31 throw new IllegalArgumentException("IV must be " + blockSize
32 + " bytes long! (currently " + iv.length + ")");
33
34 this.cbc_vector = new byte[blockSize];
35 this.tmp_vector = new byte[blockSize];
36 System.arraycopy(iv, 0, cbc_vector, 0, blockSize);
37 }
38
39 public int getBlockSize() {
40 return blockSize;
41 }
42
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];
46
47 tc.transformBlock(cbc_vector, 0, dst, dstoff);
48 System.arraycopy(dst, dstoff, cbc_vector, 0, blockSize);
49 }
50
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);
55
56 for (int i = 0; i < blockSize; i++)
57 dst[dstoff + i] ^= cbc_vector[i];
58
59 /* ...that is why we need a tmp buffer. */
60 byte[] swap = cbc_vector;
61 cbc_vector = tmp_vector;
62 tmp_vector = swap;
63 }
64
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 }
71 }