Last active
September 25, 2023 17:15
-
-
Save iKunalChhabra/ad0379d0cb0fc24152f24232afa9aeab to your computer and use it in GitHub Desktop.
Do AES encryption in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
import javax.crypto.Cipher; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import javax.crypto.spec.SecretKeySpec; | |
import java.security.spec.KeySpec; | |
import java.util.Base64; | |
public class AES { | |
private static final String ALGORITHM = "AES"; | |
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; | |
private static final String SECRET_KEY = "secret-key"; | |
private static final String SALT = "salt"; | |
private static final SecretKey secretKey = getKeyFromPassword(); | |
public static SecretKey getKeyFromPassword() { | |
try { | |
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); | |
KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256); | |
return new SecretKeySpec(factory.generateSecret(spec) | |
.getEncoded(), ALGORITHM); | |
} catch (Exception e) { | |
throw new RuntimeException("Error while generating secret key", e); | |
} | |
} | |
public static String encrypt(String input) throws Exception { | |
Cipher cipher = Cipher.getInstance(TRANSFORMATION); | |
cipher.init(Cipher.ENCRYPT_MODE, secretKey); | |
byte[] cipherText = cipher.doFinal(input.getBytes()); | |
return Base64.getEncoder().encodeToString(cipherText); | |
} | |
public static String decrypt(String value) throws Exception { | |
Cipher cipher = Cipher.getInstance(TRANSFORMATION); | |
cipher.init(Cipher.DECRYPT_MODE, secretKey); | |
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(value)); | |
return new String(plainText); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment