Skip to content

Commit 433c66b

Browse files
Create pran1
1 parent f1f8b2a commit 433c66b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

pran1

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import javax.crypto.*;
2+
import java.security.*;
3+
import java.util.Base64;
4+
5+
public class SecureCommunication {
6+
7+
public static void main(String[] args) {
8+
try {
9+
// Generate a secret key for symmetric encryption
10+
SecretKey secretKey = generateSecretKey();
11+
12+
// Simulate two parties communicating over a secure channel
13+
String messageToSend = "Hello, secure world!";
14+
byte[] encryptedMessage = encryptMessage(messageToSend, secretKey);
15+
String decryptedMessage = decryptMessage(encryptedMessage, secretKey);
16+
17+
System.out.println("Original Message: " + messageToSend);
18+
System.out.println("Encrypted Message: " + Base64.getEncoder().encodeToString(encryptedMessage));
19+
System.out.println("Decrypted Message: " + decryptedMessage);
20+
} catch (Exception e) {
21+
e.printStackTrace();
22+
}
23+
}
24+
25+
private static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
26+
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
27+
keyGenerator.init(256); // Key size, you can choose other sizes like 128 or 192
28+
return keyGenerator.generateKey();
29+
}
30+
31+
private static byte[] encryptMessage(String message, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
32+
Cipher cipher = Cipher.getInstance("AES");
33+
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
34+
return cipher.doFinal(message.getBytes());
35+
}
36+
37+
private static String decryptMessage(byte[] encryptedMessage, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
38+
Cipher cipher = Cipher.getInstance("AES");
39+
cipher.init(Cipher.DECRYPT_MODE, secretKey);
40+
byte[] decryptedBytes = cipher.doFinal(encryptedMessage);
41+
return new String(decryptedBytes);
42+
}
43+
}

0 commit comments

Comments
 (0)