-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathb1.java
More file actions
68 lines (57 loc) · 2.7 KB
/
Copy pathb1.java
File metadata and controls
68 lines (57 loc) · 2.7 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
import javax.Krypto.Cipher;
import javax.Krypto.KeyGenerator;
import javax.Krypto.SecretKey;
import javax.Krypto.spec.IvParameterSpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.security.SecureRandom;
public class class2 {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final int KEY_SIZE = 256;
private static final int IV_SIZE = 16;
public static void main(String[] args) throws Exception {
String resourcesPath = "path/to/your/resources/";
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(KEY_SIZE);
SecretKey secretKey = keyGen.generateKey();
byte[] iv = new byte[IV_SIZE];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
File inputFile = new File(resourcesPath + "input/plainTextFile.txt");
File encryptedFile = new File(resourcesPath + "output/cipherTextFile.txt");
encryptFile(secretKey, ivParameterSpec, inputFile, encryptedFile);
File decryptedFile = new File(resourcesPath + "output/plainTextDecFile.txt");
decryptFile(secretKey, ivParameterSpec, encryptedFile, decryptedFile);
System.out.println("Encryption and decryption completed successfully.");
}
private static void encryptFile(SecretKey key, IvParameterSpec iv, File inputFile, File outputFile) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
processFile(cipher, inputFile, outputFile);
}
private static void decryptFile(SecretKey key, IvParameterSpec iv, File inputFile, File outputFile) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
processFile(cipher, inputFile, outputFile);
}
private static void processFile(Cipher cipher, File inputFile, File outputFile) throws Exception {
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile)) {
byte[] inputBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(inputBuffer)) != -1) {
byte[] outputBuffer = cipher.update(inputBuffer, 0, bytesRead);
if (outputBuffer != null) {
fos.write(outputBuffer);
}
}
byte[] outputBytes = cipher.doFinal();
if (outputBytes != null) {
fos.write(outputBytes);
}
}
}
}