Java AES encryption and Decrpytion using ECB mode in Java (spring boot)
import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class AesEncryption { private static SecretKeySpec secretKey; private static byte[] key;
public static void main(String[] args) { String testString = "codemummytest"; String testKey = "codemummykey"; String testEncryptedString = encrypt(testString, testKey); System.out.println("the original string is "+testString);
System.out.println("the encrypted string is "+testEncryptedString); String testDecryptedString = decrypt(testEncryptedString, testKey); System.out.println("the encrpyted string after decrypting is "+testDecryptedString); } /** * Generate and returns the SecretKeySpec . * @param myKey * @return */ private static SecretKeySpec 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); return new SecretKeySpec(key, "AES"); } catch (Exception e) { System.out.println("Exception in SecretKeySpec method :", e.fillInStackTrace());
} return secretKey; } /** * The encrypt method returns the encrypted data in string. * * @param strToEncrypt * @param secret * @return */ public static String encrypt(String strToEncrypt, String secret) { try { Cipher cipher = getCipher(secret, Cipher.ENCRYPT_MODE); byte[] cipherText = cipher.doFinal(strToEncrypt.getBytes("UTF-8");
return Base64.getEncoder().encodeToString(cipherText); } catch (Exception e) { System.out.println("Exception in Encrypt method :", e.fillInStackTrace());
} return null; } /** * The decrypt method returns the encrypted data in string. * * @param strToDecrypt * @param secret * @return */ public static String decrypt(String strToDecrypt, String secret) { try { Cipher cipher = getCipher(secret, Cipher.DECRYPT_MODE); byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)); return new String(plainText); } catch (Exception e) { System.out.println("Exception in Decrypt method :", e.fillInStackTrace());
} return null; } /** * creates and returns cipher. * * @param secret * @param cipherMode * @return * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ private static Cipher getCipher(String secret, int cipherMode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { SecretKeySpec secretKey = setKey(secret); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(cipherMode, secretKey); return cipher; } }
output:
the original string is codemummytest
the encrypted string is Zo3PXASHY2LaAdr3ROItxw==
the encrpyted string after decrypting is codemummytest
No comments