· 9 years ago · Sep 27, 2016, 08:28 PM
1public class CryptoUtils {
2Â Â Â Â private static final String ALGORITHM = "AES";
3Â Â Â Â private static final String TRANSFORMATION = "AES";
4Â
5Â Â Â Â public static void encrypt(String key, File inputFile, File outputFile)
6Â Â Â Â Â Â Â Â Â Â Â Â throws CryptoException {
7Â Â Â Â Â Â Â Â doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
8Â Â Â Â }
9Â
10Â Â Â Â public static void decrypt(String key, File inputFile, File outputFile)
11Â Â Â Â Â Â Â Â Â Â Â Â throws CryptoException {
12Â Â Â Â Â Â Â Â doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
13Â Â Â Â }
14Â
15Â Â Â Â private static void doCrypto(int cipherMode, String key, File inputFile,
16Â Â Â Â Â Â Â Â Â Â Â Â File outputFile) throws CryptoException {
17Â Â Â Â Â Â Â Â try {
18Â Â Â Â Â Â Â Â Â Â Â Â Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
19Â Â Â Â Â Â Â Â Â Â Â Â Cipher cipher = Cipher.getInstance(TRANSFORMATION);
20Â Â Â Â Â Â Â Â Â Â Â Â cipher.init(cipherMode, secretKey);
21Â Â Â Â Â Â Â Â Â Â Â Â Â
22Â Â Â Â Â Â Â Â Â Â Â Â FileInputStream inputStream = new FileInputStream(inputFile);
23Â Â Â Â Â Â Â Â Â Â Â Â byte[] inputBytes = new byte[(int) inputFile.length()];
24Â Â Â Â Â Â Â Â Â Â Â Â inputStream.read(inputBytes);
25Â Â Â Â Â Â Â Â Â Â Â Â Â
26Â Â Â Â Â Â Â Â Â Â Â Â byte[] outputBytes = cipher.doFinal(inputBytes);
27Â Â Â Â Â Â Â Â Â Â Â Â Â
28Â Â Â Â Â Â Â Â Â Â Â Â FileOutputStream outputStream = new FileOutputStream(outputFile);
29Â Â Â Â Â Â Â Â Â Â Â Â outputStream.write(outputBytes);
30Â Â Â Â Â Â Â Â Â Â Â Â Â
31Â Â Â Â Â Â Â Â Â Â Â Â inputStream.close();
32Â Â Â Â Â Â Â Â Â Â Â Â outputStream.close();
33Â Â Â Â Â Â Â Â Â Â Â Â Â
34Â Â Â Â Â Â Â Â } catch (NoSuchPaddingException | NoSuchAlgorithmException
35Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â | InvalidKeyException | BadPaddingException
36Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â | IllegalBlockSizeException | IOException ex) {
37Â Â Â Â Â Â Â Â Â Â Â Â throw new CryptoException("Error encrypting/decrypting file", ex);
38Â Â Â Â Â Â Â Â }
39Â Â Â Â }
40}