@Override
public byte[] encrypt(@NotNull EncryptionKey key, @NotNull SymmetricAlgorithm symmetricAlgorithm, @NotNull String symmetricAlgorithmCipher, int symmetricKeySize, @NotNull byte[] data, @NotNull String cipherAlgorithm) throws EncryptionException {
checkJceKey(key);
ByteArrayDataOutputStream buf = new ByteArrayDataOutputStream();
try {
try {
byte[] encryptedData = crypt(key, data, true, cipherAlgorithm);
buf.writeShort(0);
buf.write(encryptedData);
} catch (IllegalBlockSizeException e) {
if (symmetricAlgorithm != SymmetricAlgorithm.AES) {
throw new IllegalArgumentException("Unsupported asymmetric cryptography");
}
AESKey sKey = generateKey(AESKey.class, symmetricKeySize);
byte[] encryptedSecretKey = encrypt(key, sKey.getEncoded().getEncodedKey(), cipherAlgorithm);
buf.writeShort(encryptedSecretKey.length);
buf.write(encryptedSecretKey);
buf.write(encrypt(sKey, data, symmetricAlgorithmCipher));
sKey.destroy();
} catch (InvalidKeyException e) {
throw new EncryptionException(e);
} catch (BadPaddingException e) {
throw new EncryptionException(e);
}
} catch (IOException e) {
throw new UnexpectedException(e);
}
return buf.toByteArray();
}