test formatter
This commit is contained in:
@@ -8,7 +8,8 @@ import java.security.cert.Certificate;
|
||||
|
||||
public class Encryptor {
|
||||
|
||||
public byte[] encryptMessage(byte[] message, byte[] keyBytes) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
|
||||
public byte[] encryptMessage(byte[] message, byte[] keyBytes) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException,
|
||||
BadPaddingException, IllegalBlockSizeException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||
@@ -16,14 +17,16 @@ public class Encryptor {
|
||||
return encryptedMessage;
|
||||
}
|
||||
|
||||
public byte[] encryptMessage(byte[] message, Certificate publicKeyCertificate) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
|
||||
public byte[] encryptMessage(byte[] message, Certificate publicKeyCertificate) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException,
|
||||
BadPaddingException, IllegalBlockSizeException {
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKeyCertificate);
|
||||
byte[] encryptedMessage = cipher.doFinal(message);
|
||||
return encryptedMessage;
|
||||
}
|
||||
|
||||
public byte[] decryptMessage(byte[] encryptedMessage, byte[] keyBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
|
||||
public byte[] decryptMessage(byte[] encryptedMessage, byte[] keyBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
|
||||
BadPaddingException, IllegalBlockSizeException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
||||
@@ -31,5 +34,4 @@ public class Encryptor {
|
||||
return clearMessage;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ class FileEncrypterDecrypter {
|
||||
byte[] iv = cipher.getIV();
|
||||
|
||||
try (
|
||||
FileOutputStream fileOut = new FileOutputStream(fileName);
|
||||
CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher)
|
||||
FileOutputStream fileOut = new FileOutputStream(fileName);
|
||||
CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher)
|
||||
) {
|
||||
fileOut.write(iv);
|
||||
cipherOut.write(content.getBytes());
|
||||
@@ -41,10 +41,10 @@ class FileEncrypterDecrypter {
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileIv));
|
||||
|
||||
try (
|
||||
CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
|
||||
InputStreamReader inputReader = new InputStreamReader(cipherIn);
|
||||
BufferedReader reader = new BufferedReader(inputReader)
|
||||
) {
|
||||
CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
|
||||
InputStreamReader inputReader = new InputStreamReader(cipherIn);
|
||||
BufferedReader reader = new BufferedReader(inputReader)
|
||||
) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
|
||||
@@ -26,14 +26,15 @@ public class JavaKeyStore {
|
||||
private String keyStoreType;
|
||||
private String keyStorePassword;
|
||||
|
||||
JavaKeyStore(String keyStoreType, String keyStorePassword, String keyStoreName) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
|
||||
JavaKeyStore(String keyStoreType, String keyStorePassword, String keyStoreName) throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
|
||||
IOException {
|
||||
this.keyStoreName = keyStoreName;
|
||||
this.keyStoreType = keyStoreType;
|
||||
this.keyStorePassword = keyStorePassword;
|
||||
}
|
||||
|
||||
void createEmptyKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
|
||||
if(keyStoreType ==null || keyStoreType.isEmpty()){
|
||||
if (keyStoreType == null || keyStoreType.isEmpty()) {
|
||||
keyStoreType = KeyStore.getDefaultType();
|
||||
}
|
||||
keyStore = KeyStore.getInstance(keyStoreType);
|
||||
@@ -86,12 +87,10 @@ public class JavaKeyStore {
|
||||
keyStore.deleteEntry(alias);
|
||||
}
|
||||
keyStore = null;
|
||||
|
||||
|
||||
Path keyStoreFile = Paths.get(keyStoreName);
|
||||
Files.delete(keyStoreFile);
|
||||
}
|
||||
|
||||
KeyStore getKeyStore() {
|
||||
return this.keyStore;
|
||||
}
|
||||
KeyStore getKeyStore() { return this.keyStore; }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.baeldung.securitymanager;
|
||||
import java.security.BasicPermission;
|
||||
|
||||
public class CustomPermission extends BasicPermission {
|
||||
|
||||
public CustomPermission(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@@ -45,9 +45,7 @@ public class EnableTLSv12 {
|
||||
enableTLSv12.enableTLSv12UsingSSLParameters();
|
||||
}
|
||||
|
||||
private void setPort(String[] args) {
|
||||
url = args[0];
|
||||
}
|
||||
private void setPort(String[] args) { url = args[0]; }
|
||||
|
||||
private void setHost(String[] args) {
|
||||
String portNumber = args[1];
|
||||
@@ -56,7 +54,8 @@ public class EnableTLSv12 {
|
||||
|
||||
private void handleCommunication(SSLSocket socket, String usedTLSProcess) throws IOException {
|
||||
logger.debug("Enabled TLS v1.2 on " + usedTLSProcess);
|
||||
try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
|
||||
try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
|
||||
out.println("GET / HTTP/1.0");
|
||||
out.println();
|
||||
out.flush();
|
||||
|
||||
@@ -7,7 +7,7 @@ import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
|
||||
public class SecureConnection {
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 2) {
|
||||
System.out.println("Use: SecureConnection host port");
|
||||
@@ -20,20 +20,20 @@ public class SecureConnection {
|
||||
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
|
||||
InputStream in = sslsocket.getInputStream();
|
||||
OutputStream out = sslsocket.getOutputStream();
|
||||
|
||||
|
||||
out.write(1);
|
||||
|
||||
|
||||
while (in.available() > 0) {
|
||||
System.out.print(in.read());
|
||||
}
|
||||
|
||||
|
||||
System.out.println("Secured connection performed successfully");
|
||||
|
||||
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the host from arguments
|
||||
* @param args the arguments
|
||||
@@ -42,7 +42,7 @@ public class SecureConnection {
|
||||
private static String getHost(String[] args) {
|
||||
return args[0];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the port from arguments
|
||||
* @param args the arguments
|
||||
|
||||
@@ -11,14 +11,15 @@ import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
|
||||
public class SimpleClient {
|
||||
|
||||
static String startClient(String host, int port) throws IOException {
|
||||
SocketFactory factory = SSLSocketFactory.getDefault();
|
||||
|
||||
try (Socket connection = factory.createSocket(host, port)) {
|
||||
((SSLSocket) connection).setEnabledCipherSuites(
|
||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" });
|
||||
((SSLSocket) connection).setEnabledProtocols(
|
||||
new String[] { "TLSv1.2"});
|
||||
new String[] { "TLSv1.2" });
|
||||
SSLParameters sslParams = new SSLParameters();
|
||||
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
|
||||
((SSLSocket) connection).setSSLParameters(sslParams);
|
||||
|
||||
@@ -10,15 +10,16 @@ import javax.net.ssl.SSLServerSocket;
|
||||
import javax.net.ssl.SSLServerSocketFactory;
|
||||
|
||||
public class SimpleServer {
|
||||
|
||||
static void startServer(int port) throws IOException {
|
||||
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
|
||||
|
||||
try (ServerSocket listener = factory.createServerSocket(port)) {
|
||||
((SSLServerSocket) listener).setNeedClientAuth(true);
|
||||
((SSLServerSocket) listener).setEnabledCipherSuites(
|
||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" });
|
||||
((SSLServerSocket) listener).setEnabledProtocols(
|
||||
new String[] { "TLSv1.2"});
|
||||
new String[] { "TLSv1.2" });
|
||||
while (true) {
|
||||
try (Socket socket = listener.accept()) {
|
||||
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.cipher;
|
||||
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -12,39 +11,40 @@ import java.security.cert.X509Certificate;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class EncryptorUnitTest {
|
||||
|
||||
private String encKeyString;
|
||||
private String message;
|
||||
private String certificateString;
|
||||
private String certificateString;
|
||||
private Encryptor encryptor;
|
||||
|
||||
@Before
|
||||
public void init(){
|
||||
encKeyString = "1234567890123456";
|
||||
public void init() {
|
||||
encKeyString = "1234567890123456";
|
||||
message = "This is a secret message";
|
||||
encryptor = new Encryptor();
|
||||
encryptor = new Encryptor();
|
||||
certificateString = "-----BEGIN CERTIFICATE-----\n" +
|
||||
"MIICVjCCAb8CAg37MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwG\n" +
|
||||
"A1UEC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J0IFN1cHBvcnQxGDAWBgNVBAMTD0ZyYW5rNEREIFdl\n" +
|
||||
"YiBDQTEjMCEGCSqGSIb3DQEJARYUc3VwcG9ydEBmcmFuazRkZC5jb20wHhcNMTIw\n" +
|
||||
"ODIyMDUyNzIzWhcNMTcwODIxMDUyNzIzWjBKMQswCQYDVQQGEwJKUDEOMAwGA1UE\n" +
|
||||
"CAwFVG9reW8xETAPBgNVBAoMCEZyYW5rNEREMRgwFgYDVQQDDA93d3cuZXhhbXBs\n" +
|
||||
"ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMYBBrx5PlP0WNI/ZdzD\n" +
|
||||
"+6Pktmurn+F2kQYbtc7XQh8/LTBvCo+P6iZoLEmUA9e7EXLRxgU1CVqeAi7QcAn9\n" +
|
||||
"MwBlc8ksFJHB0rtf9pmf8Oza9E0Bynlq/4/Kb1x+d+AyhL7oK9tQwB24uHOueHi1\n" +
|
||||
"C/iVv8CSWKiYe6hzN1txYe8rAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAASPdjigJ\n" +
|
||||
"kXCqKWpnZ/Oc75EUcMi6HztaW8abUMlYXPIgkV2F7YanHOB7K4f7OOLjiz8DTPFf\n" +
|
||||
"jC9UeuErhaA/zzWi8ewMTFZW/WshOrm3fNvcMrMLKtH534JKvcdMg6qIdjTFINIr\n" +
|
||||
"evnAhf0cwULaebn+lMs8Pdl7y37+sfluVok=\n" +
|
||||
"-----END CERTIFICATE-----";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEncryptionKey_whenMessageIsPassedToEncryptor_thenMessageIsEncrypted() throws Exception {
|
||||
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(),encKeyString.getBytes());
|
||||
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(), encKeyString.getBytes());
|
||||
|
||||
assertThat(encryptedMessage).isNotNull();
|
||||
assertThat(encryptedMessage.length % 32).isEqualTo(0);
|
||||
assertThat(encryptedMessage.length % 32).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,15 +53,15 @@ public class EncryptorUnitTest {
|
||||
InputStream is = new ByteArrayInputStream(certificateString.getBytes());
|
||||
X509Certificate certificate = (X509Certificate) factory.generateCertificate(is);
|
||||
|
||||
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(),certificate);
|
||||
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(), certificate);
|
||||
|
||||
assertThat(encryptedMessage).isNotNull();
|
||||
assertThat(encryptedMessage.length % 128).isEqualTo(0);
|
||||
assertThat(encryptedMessage.length % 128).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEncryptionKey_whenMessageIsEncrypted_thenDecryptMessage() throws Exception{
|
||||
byte[] encryptedMessageBytes = encryptor.encryptMessage(message.getBytes(),encKeyString.getBytes());
|
||||
public void givenEncryptionKey_whenMessageIsEncrypted_thenDecryptMessage() throws Exception {
|
||||
byte[] encryptedMessageBytes = encryptor.encryptMessage(message.getBytes(), encKeyString.getBytes());
|
||||
|
||||
byte[] clearMessageBytes = encryptor.decryptMessage(encryptedMessageBytes, encKeyString.getBytes());
|
||||
|
||||
|
||||
@@ -17,7 +17,10 @@ import static org.junit.Assert.assertThat;
|
||||
public class FileEncrypterDecrypterIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException {
|
||||
public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException,
|
||||
NoSuchPaddingException, InvalidKeyException,
|
||||
IOException,
|
||||
InvalidAlgorithmParameterException {
|
||||
String originalContent = "foobar";
|
||||
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
|
||||
|
||||
|
||||
@@ -176,7 +176,8 @@ public class JavaKeyStoreUnitTest {
|
||||
Assert.assertTrue(result == null);
|
||||
}
|
||||
|
||||
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
|
||||
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException,
|
||||
NoSuchAlgorithmException, InvalidKeyException, SignatureException {
|
||||
X509CertInfo certInfo = new X509CertInfo();
|
||||
// Serial number and version
|
||||
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new SecureRandom())));
|
||||
@@ -197,23 +198,23 @@ public class JavaKeyStoreUnitTest {
|
||||
Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years
|
||||
CertificateValidity validity = new CertificateValidity(validFrom, validTo);
|
||||
certInfo.set(X509CertInfo.VALIDITY, validity);
|
||||
|
||||
|
||||
GeneralNameInterface dnsName = new DNSName("baeldung.com");
|
||||
DerOutputStream dnsNameOutputStream = new DerOutputStream();
|
||||
dnsName.encode(dnsNameOutputStream);
|
||||
|
||||
|
||||
GeneralNameInterface ipAddress = new IPAddressName("127.0.0.1");
|
||||
DerOutputStream ipAddressOutputStream = new DerOutputStream();
|
||||
ipAddress.encode(ipAddressOutputStream);
|
||||
|
||||
|
||||
GeneralNames generalNames = new GeneralNames();
|
||||
generalNames.add(new GeneralName(dnsName));
|
||||
generalNames.add(new GeneralName(ipAddress));
|
||||
|
||||
|
||||
CertificateExtensions ext = new CertificateExtensions();
|
||||
ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames));
|
||||
|
||||
certInfo.set(X509CertInfo.EXTENSIONS, ext);
|
||||
certInfo.set(X509CertInfo.EXTENSIONS, ext);
|
||||
|
||||
// Create certificate and sign it
|
||||
X509CertImpl cert = new X509CertImpl(certInfo);
|
||||
|
||||
Reference in New Issue
Block a user