[BAEL-1930] Encryption and decryption of files using JDK
This commit is contained in:
+33
@@ -0,0 +1,33 @@
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user