forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFile_Encryption.Java
56 lines (45 loc) · 2.12 KB
/
File_Encryption.Java
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
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Scanner;
public class FileEncryptionDecryptionTool {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file path: ");
String filePath = scanner.nextLine();
System.out.print("Enter the encryption key (16 characters): ");
String encryptionKey = scanner.nextLine();
try {
byte[] key = encryptionKey.getBytes();
key = Arrays.copyOf(key, 16); // Ensure the key is exactly 16 bytes
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
// Encrypt the file
byte[] fileData = Files.readAllBytes(Paths.get(filePath));
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(fileData);
Path encryptedFilePath = Paths.get(filePath + ".enc");
Files.write(encryptedFilePath, encryptedData, StandardOpenOption.CREATE);
System.out.println("File encrypted successfully to: " + encryptedFilePath);
// Decrypt the file
System.out.print("Do you want to decrypt the file (Y/N)? ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("Y")) {
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(encryptedData);
Path decryptedFilePath = Paths.get(filePath + ".dec");
Files.write(decryptedFilePath, decryptedData, StandardOpenOption.CREATE);
System.out.println("File decrypted successfully to: " + decryptedFilePath);
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}