LOG.debug(Messages.getString("Encrypter.Encrypting", input.remaining()));
KeyczarKey encryptingKey = getPrimaryKey();
if (encryptingKey == null) {
throw new NoPrimaryKeyException() ;
}
EncryptingStream cryptStream = ENCRYPT_QUEUE.poll();
if (cryptStream == null) {
cryptStream = (EncryptingStream) encryptingKey.getStream();
}
// Initialize the signing stream
SigningStream signStream = cryptStream.getSigningStream();
signStream.initSign();
// Write the key header
output.mark();
ByteBuffer outputToSign = output.asReadOnlyBuffer();
encryptingKey.copyHeader(output);
// Write the IV. May be an empty array of zero length
cryptStream.initEncrypt(output);
ByteBuffer inputCopy = input.asReadOnlyBuffer();
while (inputCopy.remaining() > ENCRYPT_CHUNK_SIZE) {
ByteBuffer inputChunk = inputCopy.slice();
inputChunk.limit(ENCRYPT_CHUNK_SIZE);
cryptStream.updateEncrypt(inputChunk, output);
inputCopy.position(inputCopy.position() + ENCRYPT_CHUNK_SIZE);
outputToSign.limit(output.position());
signStream.updateSign(outputToSign);
outputToSign.position(output.position());
}
// Sign any remaining plaintext
cryptStream.doFinalEncrypt(inputCopy, output);
output.limit(output.position() + signStream.digestSize());
// Set the limit on the output to sign
outputToSign.limit(output.position());
signStream.updateSign(outputToSign);