Skip to content

Instantly share code, notes, and snippets.

@junkdog
Created March 13, 2020 12:46
Show Gist options
  • Save junkdog/39a47ac38c41d6d290046b877bd3343e to your computer and use it in GitHub Desktop.
Save junkdog/39a47ac38c41d6d290046b877bd3343e to your computer and use it in GitHub Desktop.
NIST SP 800-38A
package org.bouncycastle.crypto;
/**
* A wrapper class that allows block ciphers to be used to process data in
* a piecemeal fashion. The BufferedBlockCipher outputs a block only when the
* buffer is full and more data is being added, or on a doFinal.
* <p>
* Note: in the case where the underlying cipher is either a CFB cipher or an
* OFB one the last block may not be a multiple of the block size.
*/
public class BufferedBlockCipher
{
protected byte[] buf;
protected int bufOff;
protected boolean forEncryption;
protected BlockCipher cipher;
protected boolean partialBlockOkay;
protected boolean pgpCFB;
/**
* constructor for subclasses
*/
protected BufferedBlockCipher()
{
}
/**
* Create a buffered block cipher without padding.
*
* @param cipher the underlying block cipher this buffering object wraps.
*/
public BufferedBlockCipher(
BlockCipher cipher)
{
this.cipher = cipher;
buf = new byte[cipher.getBlockSize()];
bufOff = 0;
//
// check if we can handle partial blocks on doFinal.
//
String name = cipher.getAlgorithmName();
int idx = name.indexOf('/') + 1;
pgpCFB = (idx > 0 && name.startsWith("PGP", idx));
if (pgpCFB || cipher instanceof StreamCipher)
{
partialBlockOkay = true;
}
else
{
partialBlockOkay = (idx > 0 && (name.startsWith("OpenPGP", idx)));
}
}
/**
* return the cipher this object wraps.
*
* @return the cipher this object wraps.
*/
public BlockCipher getUnderlyingCipher()
{
return cipher;
}
/**
* initialise the cipher.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param params the key and other data required by the cipher.
* @exception IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(
boolean forEncryption,
CipherParameters params)
throws IllegalArgumentException
{
this.forEncryption = forEncryption;
reset();
cipher.init(forEncryption, params);
}
/**
* return the blocksize for the underlying cipher.
*
* @return the blocksize for the underlying cipher.
*/
public int getBlockSize()
{
return cipher.getBlockSize();
}
/**
* return the size of the output buffer required for an update
* an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update
* with len bytes of input.
*/
public int getUpdateOutputSize(
int len)
{
int total = len + bufOff;
int leftOver;
if (pgpCFB)
{
if (forEncryption)
{
leftOver = total % buf.length - (cipher.getBlockSize() + 2);
}
else
{
leftOver = total % buf.length;
}
}
else
{
leftOver = total % buf.length;
}
return total - leftOver;
}
/**
* return the size of the output buffer required for an update plus a
* doFinal with an input of 'length' bytes.
*
* @param length the length of the input.
* @return the space required to accommodate a call to update and doFinal
* with 'length' bytes of input.
*/
public int getOutputSize(
int length)
{
// Note: Can assume partialBlockOkay is true for purposes of this calculation
return length + bufOff;
}
/**
* process a single byte, producing an output block if necessary.
*
* @param in the input byte.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception IllegalStateException if the cipher isn't initialised.
*/
public int processByte(
byte in,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
int resultLen = 0;
buf[bufOff++] = in;
if (bufOff == buf.length)
{
resultLen = cipher.processBlock(buf, 0, out, outOff);
bufOff = 0;
}
return resultLen;
}
/**
* process an array of bytes, producing output if necessary.
*
* @param in the input byte array.
* @param inOff the offset at which the input data starts.
* @param len the number of bytes to be copied out of the input array.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception IllegalStateException if the cipher isn't initialised.
*/
public int processBytes(
byte[] in,
int inOff,
int len,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
if (len < 0)
{
throw new IllegalArgumentException("Can't have a negative input length!");
}
int blockSize = getBlockSize();
int length = getUpdateOutputSize(len);
if (length > 0)
{
if ((outOff + length) > out.length)
{
throw new OutputLengthException("output buffer too short");
}
}
int resultLen = 0;
int gapLen = buf.length - bufOff;
if (len > gapLen)
{
System.arraycopy(in, inOff, buf, bufOff, gapLen);
resultLen += cipher.processBlock(buf, 0, out, outOff);
bufOff = 0;
len -= gapLen;
inOff += gapLen;
while (len > buf.length)
{
resultLen += cipher.processBlock(in, inOff, out, outOff + resultLen);
len -= blockSize;
inOff += blockSize;
}
}
System.arraycopy(in, inOff, buf, bufOff, len);
bufOff += len;
if (bufOff == buf.length)
{
resultLen += cipher.processBlock(buf, 0, out, outOff + resultLen);
bufOff = 0;
}
return resultLen;
}
/**
* Process the last block in the buffer.
*
* @param out the array the block currently being held is copied into.
* @param outOff the offset at which the copying starts.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there is insufficient space in out for
* the output, or the input is not block size aligned and should be.
* @exception IllegalStateException if the underlying cipher is not
* initialised.
* @exception InvalidCipherTextException if padding is expected and not found.
* @exception DataLengthException if the input is not block size
* aligned.
*/
public int doFinal(
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException, InvalidCipherTextException
{
try
{
int resultLen = 0;
if (outOff + bufOff > out.length)
{
throw new OutputLengthException("output buffer too short for doFinal()");
}
if (bufOff != 0)
{
if (!partialBlockOkay)
{
throw new DataLengthException("data not block size aligned");
}
cipher.processBlock(buf, 0, buf, 0);
resultLen = bufOff;
bufOff = 0;
System.arraycopy(buf, 0, out, outOff, resultLen);
}
return resultLen;
}
finally
{
reset();
}
}
/**
* Reset the buffer and cipher. After resetting the object is in the same
* state as it was after the last init (if there was one).
*/
public void reset()
{
//
// clean the buffer.
//
for (int i = 0; i < buf.length; i++)
{
buf[i] = 0;
}
bufOff = 0;
//
// reset the underlying cipher.
//
cipher.reset();
}
}
package org.bouncycastle.crypto.modes;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.Arrays;
/**
* implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
*/
public class CBCBlockCipher
implements BlockCipher
{
private byte[] IV;
private byte[] cbcV;
private byte[] cbcNextV;
private int blockSize;
private BlockCipher cipher = null;
private boolean encrypting;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of chaining.
*/
public CBCBlockCipher(
BlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.getBlockSize();
this.IV = new byte[blockSize];
this.cbcV = new byte[blockSize];
this.cbcNextV = new byte[blockSize];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public BlockCipher getUnderlyingCipher()
{
return cipher;
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
*
* @param encrypting if true the cipher is initialised for
* encryption, if false for decryption.
* @param params the key and other data required by the cipher.
* @exception IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(
boolean encrypting,
CipherParameters params)
throws IllegalArgumentException
{
boolean oldEncrypting = this.encrypting;
this.encrypting = encrypting;
if (params instanceof ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)params;
byte[] iv = ivParam.getIV();
if (iv.length != blockSize)
{
throw new IllegalArgumentException("initialisation vector must be the same length as block size");
}
System.arraycopy(iv, 0, IV, 0, iv.length);
reset();
// if null it's an IV changed only.
if (ivParam.getParameters() != null)
{
cipher.init(encrypting, ivParam.getParameters());
}
else if (oldEncrypting != encrypting)
{
throw new IllegalArgumentException("cannot change encrypting state without providing key.");
}
}
else
{
reset();
// if it's null, key is to be reused.
if (params != null)
{
cipher.init(encrypting, params);
}
else if (oldEncrypting != encrypting)
{
throw new IllegalArgumentException("cannot change encrypting state without providing key.");
}
}
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/CBC".
*/
public String getAlgorithmName()
{
return cipher.getAlgorithmName() + "/CBC";
}
/**
* return the block size of the underlying cipher.
*
* @return the block size of the underlying cipher.
*/
public int getBlockSize()
{
return cipher.getBlockSize();
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception IllegalStateException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int processBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
return (encrypting) ? encryptBlock(in, inOff, out, outOff) : decryptBlock(in, inOff, out, outOff);
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void reset()
{
System.arraycopy(IV, 0, cbcV, 0, IV.length);
Arrays.fill(cbcNextV, (byte)0);
cipher.reset();
}
/**
* Do the appropriate chaining step for CBC mode encryption.
*
* @param in the array containing the data to be encrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception IllegalStateException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int encryptBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
if ((inOff + blockSize) > in.length)
{
throw new DataLengthException("input buffer too short");
}
/*
* XOR the cbcV and the input,
* then encrypt the cbcV
*/
for (int i = 0; i < blockSize; i++)
{
cbcV[i] ^= in[inOff + i];
}
int length = cipher.processBlock(cbcV, 0, out, outOff);
/*
* copy ciphertext to cbcV
*/
System.arraycopy(out, outOff, cbcV, 0, cbcV.length);
return length;
}
/**
* Do the appropriate chaining step for CBC mode decryption.
*
* @param in the array containing the data to be decrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the decrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception IllegalStateException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int decryptBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
if ((inOff + blockSize) > in.length)
{
throw new DataLengthException("input buffer too short");
}
System.arraycopy(in, inOff, cbcNextV, 0, blockSize);
int length = cipher.processBlock(in, inOff, out, outOff);
/*
* XOR the cbcV and the output
*/
for (int i = 0; i < blockSize; i++)
{
out[outOff + i] ^= cbcV[i];
}
/*
* swap the back up buffer into next position
*/
byte[] tmp;
tmp = cbcV;
cbcV = cbcNextV;
cbcNextV = tmp;
return length;
}
}
/**
* A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
* be used to produce cipher text which is the same length as the plain text.
*/
package org.bouncycastle.crypto.modes;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.OutputLengthException;
/**
* A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
* be used to produce cipher text which is the same length as the plain text.
* <p>
* This class implements the NIST version as documented in "Addendum to NIST SP 800-38A, Recommendation for Block Cipher Modes of Operation: Three Variants of Ciphertext Stealing for CBC Mode"
* </p>
*/
public class NISTCTSBlockCipher
extends BufferedBlockCipher
{
public static final int CS1 = 1;
public static final int CS2 = 2;
public static final int CS3 = 3;
private final int type;
private final int blockSize;
/**
* Create a buffered block cipher that uses NIST Cipher Text Stealing
*
* @param type type of CTS mode (CS1, CS2, or CS3)
* @param cipher the underlying block cipher used to create the CBC block cipher this cipher uses..
*/
public NISTCTSBlockCipher(
int type,
BlockCipher cipher)
{
this.type = type;
this.cipher = new CBCBlockCipher(cipher);
blockSize = cipher.getBlockSize();
buf = new byte[blockSize * 2];
bufOff = 0;
}
/**
* return the size of the output buffer required for an update
* an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update
* with len bytes of input.
*/
public int getUpdateOutputSize(
int len)
{
int total = len + bufOff;
int leftOver = total % buf.length;
if (leftOver == 0)
{
return total - buf.length;
}
return total - leftOver;
}
/**
* return the size of the output buffer required for an update plus a
* doFinal with an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update and doFinal
* with len bytes of input.
*/
public int getOutputSize(
int len)
{
return len + bufOff;
}
/**
* process a single byte, producing an output block if necessary.
*
* @param in the input byte.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception org.bouncycastle.crypto.DataLengthException if there isn't enough space in out.
* @exception IllegalStateException if the cipher isn't initialised.
*/
public int processByte(
byte in,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
int resultLen = 0;
if (bufOff == buf.length)
{
resultLen = cipher.processBlock(buf, 0, out, outOff);
System.arraycopy(buf, blockSize, buf, 0, blockSize);
bufOff = blockSize;
}
buf[bufOff++] = in;
return resultLen;
}
/**
* process an array of bytes, producing output if necessary.
*
* @param in the input byte array.
* @param inOff the offset at which the input data starts.
* @param len the number of bytes to be copied out of the input array.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception org.bouncycastle.crypto.DataLengthException if there isn't enough space in out.
* @exception IllegalStateException if the cipher isn't initialised.
*/
public int processBytes(
byte[] in,
int inOff,
int len,
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException
{
if (len < 0)
{
throw new IllegalArgumentException("Can't have a negative input length!");
}
int blockSize = getBlockSize();
int length = getUpdateOutputSize(len);
if (length > 0)
{
if ((outOff + length) > out.length)
{
throw new OutputLengthException("output buffer too short");
}
}
int resultLen = 0;
int gapLen = buf.length - bufOff;
if (len > gapLen)
{
System.arraycopy(in, inOff, buf, bufOff, gapLen);
resultLen += cipher.processBlock(buf, 0, out, outOff);
System.arraycopy(buf, blockSize, buf, 0, blockSize);
bufOff = blockSize;
len -= gapLen;
inOff += gapLen;
while (len > blockSize)
{
System.arraycopy(in, inOff, buf, bufOff, blockSize);
resultLen += cipher.processBlock(buf, 0, out, outOff + resultLen);
System.arraycopy(buf, blockSize, buf, 0, blockSize);
len -= blockSize;
inOff += blockSize;
}
}
System.arraycopy(in, inOff, buf, bufOff, len);
bufOff += len;
return resultLen;
}
/**
* Process the last block in the buffer.
*
* @param out the array the block currently being held is copied into.
* @param outOff the offset at which the copying starts.
* @return the number of output bytes copied to out.
* @exception org.bouncycastle.crypto.DataLengthException if there is insufficient space in out for
* the output.
* @exception IllegalStateException if the underlying cipher is not
* initialised.
* @exception org.bouncycastle.crypto.InvalidCipherTextException if cipher text decrypts wrongly (in
* case the exception will never get thrown).
*/
public int doFinal(
byte[] out,
int outOff)
throws DataLengthException, IllegalStateException, InvalidCipherTextException
{
if (bufOff + outOff > out.length)
{
throw new OutputLengthException("output buffer to small in doFinal");
}
int blockSize = cipher.getBlockSize();
int len = bufOff - blockSize;
byte[] block = new byte[blockSize];
if (forEncryption)
{
if (bufOff < blockSize)
{
throw new DataLengthException("need at least one block of input for NISTCTS");
}
if (bufOff > blockSize)
{
byte[] lastBlock = new byte[blockSize];
if (this.type == CS2 || this.type == CS3)
{
cipher.processBlock(buf, 0, block, 0);
System.arraycopy(buf, blockSize, lastBlock, 0, len);
cipher.processBlock(lastBlock, 0, lastBlock, 0);
if (this.type == CS2 && len == blockSize)
{
System.arraycopy(block, 0, out, outOff, blockSize);
System.arraycopy(lastBlock, 0, out, outOff + blockSize, len);
}
else
{
System.arraycopy(lastBlock, 0, out, outOff, blockSize);
System.arraycopy(block, 0, out, outOff + blockSize, len);
}
}
else
{
System.arraycopy(buf, 0, block, 0, blockSize);
cipher.processBlock(block, 0, block, 0);
System.arraycopy(block, 0, out, outOff, len);
System.arraycopy(buf, bufOff - len, lastBlock, 0, len);
cipher.processBlock(lastBlock, 0, lastBlock, 0);
System.arraycopy(lastBlock, 0, out, outOff + len, blockSize);
}
}
else
{
cipher.processBlock(buf, 0, block, 0);
System.arraycopy(block, 0, out, outOff, blockSize);
}
}
else
{
if (bufOff < blockSize)
{
throw new DataLengthException("need at least one block of input for CTS");
}
byte[] lastBlock = new byte[blockSize];
if (bufOff > blockSize)
{
if (this.type == CS3 || (this.type == CS2 && ((buf.length - bufOff) % blockSize) != 0))
{
if (cipher instanceof CBCBlockCipher)
{
BlockCipher c = ((CBCBlockCipher)cipher).getUnderlyingCipher();
c.processBlock(buf, 0, block, 0);
}
else
{
cipher.processBlock(buf, 0, block, 0);
}
for (int i = blockSize; i != bufOff; i++)
{
lastBlock[i - blockSize] = (byte)(block[i - blockSize] ^ buf[i]);
}
System.arraycopy(buf, blockSize, block, 0, len);
cipher.processBlock(block, 0, out, outOff);
System.arraycopy(lastBlock, 0, out, outOff + blockSize, len);
}
else
{
BlockCipher c = ((CBCBlockCipher)cipher).getUnderlyingCipher();
c.processBlock(buf, bufOff - blockSize, lastBlock, 0);
System.arraycopy(buf, 0, block, 0, blockSize);
if (len != blockSize)
{
System.arraycopy(lastBlock, len, block, len, blockSize - len);
}
cipher.processBlock(block, 0, block, 0);
System.arraycopy(block, 0, out, outOff, blockSize);
for (int i = 0; i != len; i++)
{
lastBlock[i] ^= buf[i];
}
System.arraycopy(lastBlock, 0, out, outOff + blockSize, len);
}
}
else
{
cipher.processBlock(buf, 0, block, 0);
System.arraycopy(block, 0, out, outOff, blockSize);
}
}
int offset = bufOff;
reset();
return offset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment