You are on page 1of 1

Name : Abid Mahat

Roll No B14
Prn :- 2122000218

AES Implementation

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.*;

public class AES {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string:");
String originalString = sc.nextLine();
String key = "ThisIsASecretKey"; // 128 bit key
String encryptedString = encrypt(originalString, key);
System.out.println("Encrypted String: " + encryptedString);
String decryptedString = decrypt(encryptedString, key);
System.out.println("Decrypted String: " + decryptedString);
sc.close();
}
public static String encrypt(String strToEncrypt, String secret) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String strToDecrypt, String secret) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt));
return new String(decryptedBytes);
}
}

Output:-

You might also like