-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileEncryption.java
More file actions
70 lines (57 loc) · 2.52 KB
/
FileEncryption.java
File metadata and controls
70 lines (57 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
public class FileEncryption {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES";
public static void encryptFile(String key, File inputFile, File outputFile)
throws CryptoException {
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}
public static void decryptFile(String key, File inputFile, File outputFile)
throws CryptoException {
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}
private static void doCrypto(int cipherMode, String key, File inputFile,
File outputFile) throws CryptoException {
try {
Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
}
}
public static void main(String[] args) {
String key = "ThisIsASecretKey";
File inputFile = new File("input.txt");
File encryptedFile = new File("encrypted.txt");
File decryptedFile = new File("decrypted.txt");
try {
encryptFile(key, inputFile, encryptedFile);
decryptFile(key, encryptedFile, decryptedFile);
System.out.println("Encryption and decryption completed successfully.");
} catch (CryptoException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
class CryptoException extends Exception {
public CryptoException() {
}
public CryptoException(String message, Throwable throwable) {
super(message, throwable);
}
}