From 01baf5c7525383eff7deba29780de274af51d5d4 Mon Sep 17 00:00:00 2001 From: sharifi Date: Sat, 31 Oct 2020 17:41:37 +0330 Subject: [PATCH] add aes main source --- .../main/java/com/baeldung/aes/AESUtil.java | 183 ++++++++++++++++++ .../main/java/com/baeldung/aes/Student.java | 29 +++ .../com/baeldung/aes/AESUtilUnitTest.java | 89 +++++++++ 3 files changed, 301 insertions(+) create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/AESUtil.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/Student.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/aes/AESUtilUnitTest.java diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/AESUtil.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/AESUtil.java new file mode 100644 index 0000000000..c4568623d0 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/AESUtil.java @@ -0,0 +1,183 @@ +package com.baeldung.crypto; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.crypto.*; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.*; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Base64; + +public class AESUtil { + static Logger logger = LoggerFactory.getLogger(AESUtil.class); + + public static String encrypt(String algorithm, String input, SecretKey key, IvParameterSpec iv) { + try { + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.ENCRYPT_MODE, key, iv); + byte[] cipherText = cipher.doFinal(input.getBytes()); + return Base64.getEncoder().encodeToString(cipherText); + } catch (NoSuchAlgorithmException | NoSuchPaddingException + | InvalidKeyException | InvalidAlgorithmParameterException + | IllegalBlockSizeException | BadPaddingException exp) { + logger.error(exp.getMessage()); + } + return null; + } + + public static String decrypt(String algorithm, String cipherText, SecretKey key, IvParameterSpec iv) { + try { + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText)); + return new String(plainText); + } catch (NoSuchAlgorithmException | NoSuchPaddingException + | InvalidKeyException | InvalidAlgorithmParameterException + | IllegalBlockSizeException | BadPaddingException exp) { + logger.error(exp.getMessage()); + } + return null; + } + + public static SecretKey generateKey(int n) throws NoSuchAlgorithmException { + KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); + keyGenerator.init(n); + SecretKey key = keyGenerator.generateKey(); + return key; + } + + public static SecretKey getKeyFromPassword(String password, String salt) + throws NoSuchAlgorithmException, InvalidKeySpecException { + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); + KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256); + SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); + return secret; + } + + public static IvParameterSpec generateIv() { + byte[] iv = new byte[16]; + new SecureRandom().nextBytes(iv); + return new IvParameterSpec(iv); + } + + public static void encryptFile(String algorithm, SecretKey key, IvParameterSpec iv + , File inputFile, File outputFile) throws IOException { + try { + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.ENCRYPT_MODE, key, iv); + FileInputStream inputStream = new FileInputStream(inputFile); + FileOutputStream outputStream = new FileOutputStream(outputFile); + byte[] buffer = new byte[64]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + byte[] output = cipher.update(buffer, 0, bytesRead); + if (output != null) { + outputStream.write(output); + } + } + byte[] outputBytes = cipher.doFinal(); + if (outputBytes != null) { + outputStream.write(outputBytes); + } + inputStream.close(); + outputStream.close(); + } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException + | NoSuchPaddingException | BadPaddingException + | IllegalBlockSizeException | InvalidKeyException exp) { + logger.error(exp.getMessage()); + } + } + + public static void decryptFile(String algorithm, SecretKey key, IvParameterSpec iv + , File encryptedFile, File decryptedFile) throws IOException { + try { + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + FileInputStream inputStream = new FileInputStream(encryptedFile); + FileOutputStream outputStream = new FileOutputStream(decryptedFile); + byte[] buffer = new byte[64]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + byte[] output = cipher.update(buffer, 0, bytesRead); + if (output != null) { + outputStream.write(output); + } + } + byte[] output = cipher.doFinal(); + if (output != null) { + outputStream.write(output); + } + inputStream.close(); + outputStream.close(); + } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException + | NoSuchPaddingException | BadPaddingException + | IllegalBlockSizeException | InvalidKeyException exp) { + logger.error(exp.getMessage()); + } + } + + public static SealedObject encryptObject(String algorithm, Serializable object, SecretKey key, IvParameterSpec iv) { + try { + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.ENCRYPT_MODE, key, iv); + SealedObject sealedObject = new SealedObject(object, cipher); + return sealedObject; + } catch (NoSuchAlgorithmException | NoSuchPaddingException + | InvalidKeyException | InvalidAlgorithmParameterException + | IOException | IllegalBlockSizeException exp) { + logger.error(exp.getMessage()); + } + return null; + } + + public static Serializable decryptObject(String algorithm, SealedObject sealedObject + , SecretKey key, IvParameterSpec iv) { + try { + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + Serializable unsealObject = (Serializable) sealedObject.getObject(cipher); + return unsealObject; + } catch (NoSuchAlgorithmException | NoSuchPaddingException + | InvalidKeyException | InvalidAlgorithmParameterException + | IOException | ClassNotFoundException | IllegalBlockSizeException + | BadPaddingException exp) { + logger.error(exp.getMessage()); + } + return null; + } + + public static String encryptPasswordBased(String plainText, SecretKey key, IvParameterSpec iv) { + try { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, key, iv); + return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes())); + } catch (NoSuchAlgorithmException | BadPaddingException + | InvalidKeyException | InvalidAlgorithmParameterException + | NoSuchPaddingException | IllegalBlockSizeException exp) { + logger.error(exp.getMessage()); + } + return null; + } + + public static String decryptPasswordBased(String cipherText, SecretKey key, IvParameterSpec iv) { + try { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText))); + } catch (NoSuchAlgorithmException | BadPaddingException + | InvalidKeyException | InvalidAlgorithmParameterException + | NoSuchPaddingException | IllegalBlockSizeException exp) { + logger.error(exp.getMessage()); + } + return null; + } + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/Student.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/Student.java new file mode 100644 index 0000000000..be87d4b06f --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/aes/Student.java @@ -0,0 +1,29 @@ +package com.baeldung.crypto; + +import java.io.Serializable; + +public class Student implements Serializable { + private String name; + private int age; + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/aes/AESUtilUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/aes/AESUtilUnitTest.java new file mode 100644 index 0000000000..fd51ce6a62 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/aes/AESUtilUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.crypto; + +import org.assertj.core.api.WithAssertions; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.crypto.*; +import javax.crypto.spec.IvParameterSpec; +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; + +//@SpringBootTest +class AESUtilUnitTest implements WithAssertions { + + @Test + void contextLoads() { + } + + @Test + void givenString_whenEncrypt_thenSuccess() throws NoSuchAlgorithmException { + // given + String input = "baeldung"; + SecretKey key = AESUtil.generateKey(128); + IvParameterSpec ivParameterSpec = AESUtil.generateIv(); + String algorithm = "AES/CBC/PKCS5Padding"; + + // when + String cipherText = AESUtil.encrypt(algorithm, input, key, ivParameterSpec); + String plainText = AESUtil.decrypt(algorithm, cipherText, key, ivParameterSpec); + + // then + Assertions.assertEquals(input, plainText); + } + + @Test + void givenFile_whenEncrypt_thenSuccess() throws NoSuchAlgorithmException, IOException { + // given + SecretKey key = AESUtil.generateKey(128); + String algorithm = "AES/CBC/PKCS5Padding"; + IvParameterSpec ivParameterSpec = AESUtil.generateIv(); + File inputFile = Paths.get("src/test/resources/baeldung.txt").toFile(); + File encryptedFile = new File("classpath:baeldung.encrypted"); + File decryptedFile = new File("document.decrypted"); + + // when + AESUtil.encryptFile(algorithm, key, ivParameterSpec, inputFile, encryptedFile); + AESUtil.decryptFile(algorithm, key, ivParameterSpec, encryptedFile, decryptedFile); + + // then + assertThat(inputFile).hasSameTextualContentAs(decryptedFile); + } + + @Test + void givenObject_whenEncrypt_thenSuccess() throws NoSuchAlgorithmException { + // given + Student student = new Student("Baeldung", 20); + SecretKey key = AESUtil.generateKey(128); + IvParameterSpec ivParameterSpec = AESUtil.generateIv(); + String algorithm = "AES/CBC/PKCS5Padding"; + + // when + SealedObject sealedObject = AESUtil.encryptObject(algorithm, student, key, ivParameterSpec); + Student object = (Student) AESUtil.decryptObject(algorithm, sealedObject, key, ivParameterSpec); + + // then + assertThat(student).isEqualToComparingFieldByField(object); + } + + @Test + void givenPassword_whenEncrypt_thenSuccess() throws InvalidKeySpecException, NoSuchAlgorithmException { + // given + String plainText = "www.baeldung.com"; + String password = "baeldung"; + String salt = "12345678"; + IvParameterSpec ivParameterSpec = AESUtil.generateIv(); + SecretKey key = AESUtil.getKeyFromPassword(password,salt); + + // when + String cipherText = AESUtil.encryptPasswordBased(plainText, key, ivParameterSpec); + String decryptedCipherText = AESUtil.decryptPasswordBased(cipherText, key, ivParameterSpec); + + // then + Assertions.assertEquals(plainText, decryptedCipherText); + } +} +