List of usage examples for org.bouncycastle.crypto.paddings BlockCipherPadding addPadding
public int addPadding(byte[] in, int inOff);
From source file:snodes.net.Packet.java
License:Open Source License
/** * Encrypts the packet using the given key. * * @param bytes//from w ww .j a v a2 s .com * The packet data. * @param key * The packet key. * @return * The encrypted packet data. * @throws IllegalArgumentException * If <tt>key</tt> is too short. */ private static byte[] encrypt(byte[] bytes, Key key) throws IllegalArgumentException { logger.fine("Encrypting packet with key " + key); KeyParameter fishkey = new KeyParameter(key.toByteArray()); TwofishEngine twofish = new TwofishEngine(); int blocksize = twofish.getBlockSize(); int blocks = (int) Math.ceil((double) bytes.length / (double) blocksize); twofish.init(true, fishkey); // true = encrypt byte[] encrypted = new byte[blocks * blocksize]; // Leave room for padding for (int i = 0; i < blocks; i++) { byte[] block = new byte[blocksize]; int offset = i * blocksize; int written = 0; // Pad if not enough bytes -- otherwise, exception is thrown if (bytes.length - offset < blocksize) { BlockCipherPadding pad = new PKCS7Padding(); int padLen = bytes.length - offset; byte[] write = new byte[blocksize]; int padding = 0; System.arraycopy(bytes, offset, write, 0, padLen); pad.init(new SecureRandom()); padding = pad.addPadding(write, padLen); written = twofish.processBlock(write, 0, block, 0); } else { written = twofish.processBlock(bytes, offset, block, 0); } System.arraycopy(block, 0, encrypted, offset, written); } return encrypted; }