Merge pull request #4606 from kiview/bael-1930-encrypt

[BAEL-1930] Encryption and decryption of files using JDK
This commit is contained in:
Loredana Crusoveanu
2018-07-07 17:45:50 +03:00
committed by GitHub
3 changed files with 92 additions and 3 deletions
@@ -0,0 +1,32 @@
package com.baeldung.encrypt;
import org.junit.Test;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class FileEncrypterDecrypterIntegrationTest {
@Test
public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException {
String originalContent = "foobar";
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
FileEncrypterDecrypter fileEncrypterDecrypter = new FileEncrypterDecrypter(secretKey, "AES/CBC/PKCS5Padding");
fileEncrypterDecrypter.encrypt(originalContent, "baz.enc");
String decryptedContent = fileEncrypterDecrypter.decrypt("baz.enc");
assertThat(decryptedContent, is(originalContent));
new File("baz.enc").delete(); // cleanup
}
}