}
byte[] encryptedBytes = null;
// Now create the working cipher if none was created already
Cipher c;
if (contextCipher == null) {
c = constructCipher(algorithm, null);
} else {
c = contextCipher;
}
// Now perform the encryption
int ivLen = JCEMapper.getIVLengthFromURI(algorithm) / 8;
byte[] iv = XMLSecurityConstants.generateBytes(ivLen);
try {
AlgorithmParameterSpec paramSpec = constructBlockCipherParameters(algorithm, iv);
c.init(cipherMode, key, paramSpec);
} catch (InvalidKeyException ike) {
throw new XMLEncryptionException("empty", ike);
}
try {
if (serializedData != null) {
int numBytes;
byte[] buf = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((numBytes = serializedData.read(buf)) != -1) {
byte[] data = c.update(buf, 0, numBytes);
baos.write(data);
}
baos.write(c.doFinal());
encryptedBytes = baos.toByteArray();
} else {
encryptedBytes = c.doFinal(serializedOctets);
if (log.isDebugEnabled()) {
log.debug("Expected cipher.outputSize = " +
Integer.toString(c.getOutputSize(serializedOctets.length)));
}
}
if (log.isDebugEnabled()) {
log.debug("Actual cipher.outputSize = "
+ Integer.toString(encryptedBytes.length));
}
} catch (IllegalStateException ise) {
throw new XMLEncryptionException("empty", ise);
} catch (IllegalBlockSizeException ibse) {
throw new XMLEncryptionException("empty", ibse);
} catch (BadPaddingException bpe) {
throw new XMLEncryptionException("empty", bpe);
} catch (UnsupportedEncodingException uee) {
throw new XMLEncryptionException("empty", uee);
}
// Get IV from Cipher Object. If this is null (see BouncyCastle issue BJA-473) then use
// the original IV that was generated
if (c.getIV() != null) {
iv = c.getIV();
}
// Now build up to a properly XML Encryption encoded octet stream
byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length];
System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length);
System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length);