From 527919e436463d8dd61fb734435d965b2d7b0c5c Mon Sep 17 00:00:00 2001 From: Saurabh Pal Date: Sun, 24 Oct 2021 14:19:22 +0530 Subject: [PATCH] Create AES_encryption_Algo.java --- Algorithms/AES_encryption_Algo.java | 64 +++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Algorithms/AES_encryption_Algo.java diff --git a/Algorithms/AES_encryption_Algo.java b/Algorithms/AES_encryption_Algo.java new file mode 100644 index 0000000..74db090 --- /dev/null +++ b/Algorithms/AES_encryption_Algo.java @@ -0,0 +1,64 @@ +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +public class AES { + + private static SecretKeySpec secretKey; + private static byte[] key; + + public static void setKey(String myKey) + { + MessageDigest sha = null; + try { + key = myKey.getBytes("UTF-8"); + sha = MessageDigest.getInstance("SHA-1"); + key = sha.digest(key); + key = Arrays.copyOf(key, 16); + secretKey = new SecretKeySpec(key, "AES"); + } + catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public static String encrypt(String strToEncrypt, String secret) + { + try + { + setKey(secret); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); + } + catch (Exception e) + { + System.out.println("Error while encrypting: " + e.toString()); + } + return null; + } + + public static String decrypt(String strToDecrypt, String secret) + { + try + { + setKey(secret); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); + cipher.init(Cipher.DECRYPT_MODE, secretKey); + return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); + } + catch (Exception e) + { + System.out.println("Error while decrypting: " + e.toString()); + } + return null; + } +}