Example for Interface Implementations
Below is an example of the implementation of the interfaces.
Note: This example is meant for demonstration purposes only. To implement it in production, the processing should be appropriate.
@Component
public class FileImportListenerImpl implements FileImportListener {
@Override
public void preProcessImportedFile(String path) throws FileProcessException {
try {
FileEncryptDecrypt.decryptFile(path);
} catch (IOException | GeneralSecurityException e) {
throw new FileProcessException(e);
}
}
}
@Component
public class FileExportListenerImpl implements FileExportListener {
@Override
public void postProcessExportedFile(String path) throws FileProcessException {
try {
FileEncryptDecrypt.encryptFile(path);
} catch (IOException | GeneralSecurityException e) {
throw new FileProcessException(e);
}
}
}
public class FileEncryptDecrypt {
private static final String PASS = "jS43kP77L3m2CoF";
private static final byte[] SALT = {
(byte) 0x43, (byte) 0x76, (byte) 0x95, (byte) 0xc7,
(byte) 0x5b, (byte) 0xd7, (byte) 0x45, (byte) 0x17
};
private static final String TRANSFORMATION_ALGORITHM = "PBEWithMD5AndDES";
private static Cipher makeCipher(boolean decryptMode) throws GeneralSecurityException {
PBEKeySpec keySpec = new PBEKeySpec(PASS.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(TRANSFORMATION_ALGORITHM);
SecretKey key = keyFactory.generateSecret(keySpec);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(SALT, 42);
Cipher cipher = Cipher.getInstance(TRANSFORMATION_ALGORITHM);
cipher.init(decryptMode ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, key, pbeParamSpec);
return cipher;
}
static void encryptFile(String fileName) throws IOException, GeneralSecurityException {
byte[] decData;
byte[] encData;
File inFile = new File(fileName);
Cipher cipher = makeCipher(false);
try (FileInputStream inStream = new FileInputStream(inFile)) {
int blockSize = 8;
int paddedCount = blockSize - ((int) inFile.length() % blockSize);
int padded = (int) inFile.length() + paddedCount;
decData = new byte[padded];
inStream.read(decData);
for (int i = (int) inFile.length(); i < padded; ++i) {
decData[i] = (byte) paddedCount;
}
}
encData = cipher.doFinal(decData);
try (FileOutputStream outStream = new FileOutputStream(fileName)) {
outStream.write(encData);
}
}
static void decryptFile(String fileName) throws GeneralSecurityException, IOException {
byte[] encData;
byte[] decData;
File inFile = new File(fileName);
Cipher cipher = makeCipher(true);
try (FileInputStream inStream = new FileInputStream(inFile)) {
encData = new byte[(int) inFile.length()];
inStream.read(encData);
inStream.close();
decData = cipher.doFinal(encData);
int padCount = decData[decData.length - 1];
if (padCount >= 1 && padCount <= 8) {
decData = Arrays.copyOfRange(decData, 0, decData.length - padCount);
}
}
try (FileOutputStream target = new FileOutputStream(fileName)) {
target.write(decData);
}
}
}