-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathAESEncryption.java
More file actions
52 lines (42 loc) · 1.88 KB
/
AESEncryption.java
File metadata and controls
52 lines (42 loc) · 1.88 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
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Scanner;
public class AESEncryption {
// Encrypt text using AES algorithm
public static String encrypt(String plainText, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// Decrypt text using AES algorithm
public static String decrypt(String encryptedText, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("=== AES Encryption & Decryption Demo ===");
System.out.print("Enter text to encrypt: ");
String text = scanner.nextLine();
// Generate AES key (128-bit)
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
// Encrypt
String encryptedText = encrypt(text, secretKey);
System.out.println("Encrypted text: " + encryptedText);
// Decrypt
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted text: " + decryptedText);
// Print key for reference
System.out.println("Secret Key (Base64): " + Base64.getEncoder().encodeToString(secretKey.getEncoded()));
scanner.close();
}
}