This commit is contained in:
2023-07-25 23:03:47 +02:00
commit d35aa29a0e
14 changed files with 543 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
package org.orinprojects;
import org.orinprojects.encryption.Encryption;
import org.orinprojects.impl.MessageProtocol;
import org.orinprojects.impl.MessageSender;
import org.orinprojects.impl.MessageType;
import org.orinprojects.interfaces.Protocol;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class ClientHandler implements Runnable {
private final Socket clientSocket;
private final BufferedReader in;
private final PrintWriter out;
private String username;
private int requests = 0;
public ClientHandler(Socket socket) throws IOException {
this.clientSocket = socket;
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream());
out.println(Server.serverKeys.getPublic());
out.flush();
}
@Override
public void run() {
while (clientSocket.isConnected()) {
try {
String receivedMessage = in.readLine();
byte[] rsa = receivedMessage.getBytes(StandardCharsets.UTF_8);
PublicKey serverPublicKey = KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(rsa));
out.println(Encryption.encryptRSA(new String(Server.aesKey.getEncoded()), serverPublicKey));
out.flush();
} catch (Exception e) {
closeAllConnections(clientSocket, in, out);
}
}
}
// private void printKey(String username) {
// System.out.println(Encryption.getKeyByUsername(username));
// }
// private void sendMessage(ObjectOutputStream out, Message message) throws IOException {
// out.writeObject(message);
// out.flush();
// }
private void closeAllConnections(Socket socket, BufferedReader in, PrintWriter out) {
try {
if (socket != null)
socket.close();
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Server.clients.remove(this);
}
}

View File

@@ -0,0 +1,66 @@
package org.orinprojects;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.orinprojects.encryption.Encryption;
import org.orinprojects.exceptions.ArgumentsException;
import javax.crypto.SecretKey;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class Server {
public static List<ClientHandler> clients = new ArrayList<>();
public static HashMap<String, PublicKey> clientKeys = new HashMap<>();
public static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(20);
public static KeyPair serverKeys;
public static SecretKey aesKey;
public static void main(String[] args) throws IOException, ArgumentsException, NoSuchAlgorithmException {
Server.serverKeys = Encryption.generateRSAKey();
Server.aesKey = Encryption.generateAESKey();
int portNumber = getPortNumber(args);
ServerSocket server = new ServerSocket(portNumber);
while (!server.isClosed()) {
Socket clientSocket = server.accept();
ClientHandler clientHandler = new ClientHandler(clientSocket);
clients.add(clientHandler);
executor.execute(clientHandler);
}
}
private static int getPortNumber(String[] args) throws ArgumentsException {
if (args.length != 2)
throw new ArgumentsException("Not enough or too much arguments");
if (!args[0].equals("-p"))
throw new ArgumentsException("No port parameter. Use -p to specify port");
int port;
try {
port = Integer.parseInt(args[1]);
} catch (NumberFormatException numberFormatException) {
throw new ArgumentsException("Wrong number format! Example: -p 6666");
}
return port;
}
}

View File

@@ -0,0 +1,59 @@
package org.orinprojects.encryption;
import org.bouncycastle.util.encoders.Base64Encoder;
import javax.crypto.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.security.spec.X509EncodedKeySpec;
public class Encryption {
private static final int rsaKeySize = 4096;
private static final int aesKeySize = 128;
public static KeyPair generateRSAKey() throws NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(rsaKeySize);
return generator.generateKeyPair();
}
public static byte[] encryptAES(PublicKey pubKey, SecretKey aesKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, pubKey);
// byte[] encryptedMessageBytes = encryptCipher.doFinal(aesKey.getEncoded());
return encryptCipher.doFinal("hello".getBytes());
}
public static String decryptAES(PrivateKey privateKey, String aes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedAES = decryptCipher.doFinal(aes.getBytes());
return new String(decryptedAES);
}
public static String encryptRSA(String data, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return new String(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
}
public static String decryptRSA(String data, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
}
public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(aesKeySize);
return keyGenerator.generateKey();
}
}

View File

@@ -0,0 +1,9 @@
package org.orinprojects.exceptions;
public class ArgumentsException extends Exception {
public ArgumentsException(String errorMessage) {
super(errorMessage);
}
}

View File

@@ -0,0 +1,50 @@
package org.orinprojects.impl;
import org.orinprojects.interfaces.Protocol;
import java.util.Arrays;
public class MessageProtocol implements Protocol {
private byte[] text;
private MessageType messageType;
public MessageProtocol(MessageType messageType, byte[] text) {
this.messageType = messageType;
this.text = text;
}
public MessageProtocol() {}
@Override
public String encryptToString() {
return this.messageType.name() + this.text;
}
@Override
public void decryptFromString(byte[] text) {
String s = new String(text, 0, 3);
switch (s) {
case "WLC" -> this.messageType = MessageType.WLC;
case "RSA" -> this.messageType = MessageType.RSA;
case "TXT" -> this.messageType = MessageType.TXT;
case "AES" -> this.messageType = MessageType.AES;
}
this.text = Arrays.copyOfRange(text, 2, text.length);
}
@Override
public MessageType getMessageType() {
return this.messageType;
}
public String getText(){
return new String(this.text);
}
public byte[] getBytes(){
return this.text;
}
}

View File

@@ -0,0 +1,12 @@
package org.orinprojects.impl;
import java.io.PrintWriter;
public class MessageSender {
public static void sendMessage(PrintWriter out, String text) {
out.println(text);
out.flush();
}
}

View File

@@ -0,0 +1,5 @@
package org.orinprojects.impl;
public enum MessageType {
FILE, TXT, WLC, AES, RSA
}

View File

@@ -0,0 +1,16 @@
package org.orinprojects.interfaces;
import org.orinprojects.impl.MessageType;
public interface Protocol {
String encryptToString();
void decryptFromString(byte[] text);
MessageType getMessageType();
String getText();
byte[] getBytes();
}