· 8 years ago · Dec 13, 2017, 10:50 AM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package javaapplication3;
7
8import java.io.File;
9import java.io.FileInputStream;
10import java.io.FileOutputStream;
11import java.io.IOException;
12import java.security.InvalidKeyException;
13import java.security.Key;
14import java.security.NoSuchAlgorithmException;
15
16import javax.crypto.BadPaddingException;
17import javax.crypto.Cipher;
18import javax.crypto.IllegalBlockSizeException;
19import javax.crypto.NoSuchPaddingException;
20import javax.crypto.spec.SecretKeySpec;
21
22/**
23 * A utility class that encrypts or decrypts a file.
24 * @author www.codejava.net
25 *
26 */
27public class CryptoUtils {
28 private static final String TRANSFORMATION = "AES";
29
30 public static void encrypt(String ALGORITHM, String key, File inputFile, File outputFile)
31 throws CryptoException {
32 doCrypto(ALGORITHM, Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
33 }
34
35 public static void decrypt(String ALGORITHM, String key, File inputFile, File outputFile)
36 throws CryptoException {
37 doCrypto(ALGORITHM, Cipher.DECRYPT_MODE, key, inputFile, outputFile);
38 }
39
40 private static void doCrypto(String ALGORITHM, int cipherMode, String key, File inputFile,
41 File outputFile) throws CryptoException {
42 try {
43 Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
44 Cipher cipher = Cipher.getInstance(TRANSFORMATION);
45 cipher.init(cipherMode, secretKey);
46
47 FileInputStream inputStream = new FileInputStream(inputFile);
48 byte[] inputBytes = new byte[(int) inputFile.length()];
49 inputStream.read(inputBytes);
50
51 byte[] outputBytes = cipher.doFinal(inputBytes);
52
53 FileOutputStream outputStream = new FileOutputStream(outputFile);
54 outputStream.write(outputBytes);
55
56 inputStream.close();
57 outputStream.close();
58
59 } catch (NoSuchPaddingException | NoSuchAlgorithmException
60 | InvalidKeyException | BadPaddingException
61 | IllegalBlockSizeException | IOException ex) {
62 doCrypto(ALGORITHM, Cipher.DECRYPT_MODE, key, inputFile, outputFile);
63 }
64 }
65
66 public class CryptoException extends Exception {
67
68 public CryptoException() {
69 }
70
71 public CryptoException(String message, Throwable throwable) {
72 super(message, throwable);
73 }
74}
75}