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 * This is CTR mode as described in draft-ietf-secsh-newmodes-XY.txt 9 * 10 * @author Christian Plattner 11 * @version 2.50, 03/15/10 12 */ 13 public class CTRMode implements BlockCipher 14 { 15 byte[] X; 16 byte[] Xenc; 17 18 BlockCipher bc; 19 int blockSize; 20 boolean doEncrypt; 21 22 int count = 0; 23 24 public void init(boolean forEncryption, byte[] key) 25 { 26 } 27 28 public CTRMode(BlockCipher tc, byte[] iv, boolean doEnc) throws IllegalArgumentException 29 { 30 bc = tc; 31 blockSize = bc.getBlockSize(); 32 doEncrypt = doEnc; 33 34 if (blockSize != iv.length) 35 throw new IllegalArgumentException("IV must be " + blockSize + " bytes long! (currently " + iv.length + ")"); 36 37 X = new byte[blockSize]; 38 Xenc = new byte[blockSize]; 39 40 System.arraycopy(iv, 0, X, 0, blockSize); 41 } 42 43 public final int getBlockSize() 44 { 45 return blockSize; 46 } 47 48 public final void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff) 49 { 50 bc.transformBlock(X, 0, Xenc, 0); 51 52 for (int i = 0; i < blockSize; i++) 53 { 54 dst[dstoff + i] = (byte) (src[srcoff + i] ^ Xenc[i]); 55 } 56 57 for (int i = (blockSize - 1); i >= 0; i--) 58 { 59 X[i]++; 60 if (X[i] != 0) 61 break; 62 63 } 64 } 65 } 66