Added messages sending after registering

This commit is contained in:
mariano.riefolo 2024-04-09 09:03:17 +02:00
parent 5f6c3de854
commit 9265a90300
6 changed files with 714 additions and 657 deletions

287
.gitignore vendored
View File

@ -1,143 +1,144 @@
# Created by https://www.toptal.com/developers/gitignore/api/intellij,java # Created by https://www.toptal.com/developers/gitignore/api/intellij,java
# Edit at https://www.toptal.com/developers/gitignore?templates=intellij,java # Edit at https://www.toptal.com/developers/gitignore?templates=intellij,java
### Intellij ### ### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff # User-specific stuff
.idea/**/workspace.xml .idea/**/workspace.xml
.idea/**/tasks.xml .idea/**/tasks.xml
.idea/**/usage.statistics.xml .idea/**/usage.statistics.xml
.idea/**/dictionaries .idea/**/dictionaries
.idea/**/shelf .idea/**/shelf
# AWS User-specific # AWS User-specific
.idea/**/aws.xml .idea/**/aws.xml
# Generated files # Generated files
.idea/**/contentModel.xml .idea/**/contentModel.xml
# Sensitive or high-churn files # Sensitive or high-churn files
.idea/**/dataSources/ .idea/**/dataSources/
.idea/**/dataSources.ids .idea/**/dataSources.ids
.idea/**/dataSources.local.xml .idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml .idea/**/sqlDataSources.xml
.idea/**/dynamic.xml .idea/**/dynamic.xml
.idea/**/uiDesigner.xml .idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml .idea/**/dbnavigator.xml
# Gradle # Gradle
.idea/**/gradle.xml .idea/**/gradle.xml
.idea/**/libraries .idea/**/libraries
# Gradle and Maven with auto-import # Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files, # When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using # since they will be recreated, and may cause churn. Uncomment if using
# auto-import. # auto-import.
# .idea/artifacts # .idea/artifacts
# .idea/compiler.xml # .idea/compiler.xml
# .idea/jarRepositories.xml # .idea/jarRepositories.xml
# .idea/modules.xml # .idea/modules.xml
# .idea/*.iml # .idea/*.iml
# .idea/modules # .idea/modules
# *.iml # *.iml
# *.ipr # *.ipr
# CMake # CMake
cmake-build-*/ cmake-build-*/
# Mongo Explorer plugin # Mongo Explorer plugin
.idea/**/mongoSettings.xml .idea/**/mongoSettings.xml
# File-based project format # File-based project format
*.iws *.iws
# IntelliJ # IntelliJ
out/ out/
# mpeltonen/sbt-idea plugin # mpeltonen/sbt-idea plugin
.idea_modules/ .idea_modules/
# JIRA plugin # JIRA plugin
atlassian-ide-plugin.xml atlassian-ide-plugin.xml
# Cursive Clojure plugin # Cursive Clojure plugin
.idea/replstate.xml .idea/replstate.xml
# SonarLint plugin # SonarLint plugin
.idea/sonarlint/ .idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ) # Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml com_crashlytics_export_strings.xml
crashlytics.properties crashlytics.properties
crashlytics-build.properties crashlytics-build.properties
fabric.properties fabric.properties
# Editor-based Rest Client # Editor-based Rest Client
.idea/httpRequests .idea/httpRequests
# Android studio 3.1+ serialized cache file # Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser .idea/caches/build_file_checksums.ser
### Intellij Patch ### ### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml # *.iml
# modules.xml # modules.xml
# .idea/misc.xml # .idea/misc.xml
# *.ipr # *.ipr
# Sonarlint plugin # Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint # https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/ .idea/**/sonarlint/
# SonarQube Plugin # SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin # https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml .idea/**/sonarIssues.xml
# Markdown Navigator plugin # Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced # https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml .idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml .idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/ .idea/**/markdown-navigator/
# Cache file creation bug # Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257 # See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$ .idea/$CACHE_FILE$
# CodeStream plugin # CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream # https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml .idea/codestream.xml
# Azure Toolkit for IntelliJ plugin # Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij # https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml .idea/**/azureSettings.xml
### Java ### ### Java ###
# Compiled class file # Compiled class file
*.class *.class
# Log file # Log file
*.log *.log
# BlueJ files # BlueJ files
*.ctxt *.ctxt
# Mobile Tools for Java (J2ME) # Mobile Tools for Java (J2ME)
.mtj.tmp/ .mtj.tmp/
# Package Files # # Package Files #
*.jar *.jar
*.war *.war
*.nar *.nar
*.ear *.ear
*.zip *.zip
*.tar.gz *.tar.gz
*.rar *.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
replay_pid* replay_pid*
# End of https://www.toptal.com/developers/gitignore/api/intellij,java # End of https://www.toptal.com/developers/gitignore/api/intellij,java
/target/

View File

@ -1,217 +1,248 @@
package controllers; package controllers;
import models.Account; import models.Account;
import models.Conversation; import models.Conversation;
import models.Message; import models.Message;
import org.mariadb.jdbc.MariaDbBlob; import org.mariadb.jdbc.MariaDbBlob;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import views.Client; import views.Client;
import java.math.BigInteger; import java.math.BigInteger;
import java.sql.*; import java.sql.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class Database { public class Database {
public static boolean registerAccount(String username, String password, BigInteger e, String d, BigInteger n) { public static boolean registerAccount(String username, String password, BigInteger e, String d, BigInteger n) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
if (connection == null) return false; if (connection == null) return false;
PasswordEncoder encoder = new BCryptPasswordEncoder(); PasswordEncoder encoder = new BCryptPasswordEncoder();
String hashedPass = encoder.encode(password); String hashedPass = encoder.encode(password);
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
INSERT INTO accounts(username, password, e, d, n) INSERT INTO accounts(username, password, e, d, n)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
""")) { """)) {
statement.setString(1, username); statement.setString(1, username);
statement.setString(2, hashedPass); statement.setString(2, hashedPass);
statement.setBlob(3, new MariaDbBlob(e.toString().getBytes())); statement.setBlob(3, new MariaDbBlob(e.toString().getBytes()));
statement.setBytes(4, d.getBytes()); statement.setBytes(4, d.getBytes());
statement.setBlob(5, new MariaDbBlob(n.toString().getBytes())); statement.setBlob(5, new MariaDbBlob(n.toString().getBytes()));
int rowsInserted = statement.executeUpdate(); int rowsInserted = statement.executeUpdate();
return rowsInserted == 1; return rowsInserted == 1;
} catch (SQLException ex) { } catch (SQLException ex) {
System.err.println("Error while trying to create a new account: " + ex); System.err.println("Error while trying to create a new account: " + ex);
return false; return false;
} }
} catch (SQLException ex) { } catch (SQLException ex) {
System.err.println("Error while trying to open a connection: " + ex); System.err.println("Error while trying to open a connection: " + ex);
return false; return false;
} }
} }
public static Account getAccount(String username, CharSequence password) { public static Account getAccount(String username, CharSequence password) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
if (connection == null) return null; if (connection == null) return null;
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
SELECT id, password, e, d, n SELECT id, password, e, d, n
FROM accounts FROM accounts
WHERE username = ? WHERE username = ?
""")) { """)) {
statement.setString(1, username); statement.setString(1, username);
ResultSet resultSet = statement.executeQuery(); ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
int id = resultSet.getInt("id"); int id = resultSet.getInt("id");
String hash_password = resultSet.getString("password"); String hash_password = resultSet.getString("password");
BigInteger e = new BigInteger(resultSet.getString("e")); BigInteger e = new BigInteger(resultSet.getString("e"));
byte[] d = convertToByteArray(resultSet.getString("d")); byte[] d = convertToByteArray(resultSet.getString("d"));
BigInteger n = new BigInteger(resultSet.getString("n")); BigInteger n = new BigInteger(resultSet.getString("n"));
PasswordEncoder encoder = new BCryptPasswordEncoder(); PasswordEncoder encoder = new BCryptPasswordEncoder();
if (encoder.matches(password, hash_password)) if (encoder.matches(password, hash_password))
return new Account(id, username, e, d, n); return new Account(id, username, e, d, n);
} }
return null; return null;
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Error while trying to logging in: " + e); System.err.println("Error while trying to logging in: " + e);
return null; return null;
} }
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Error while trying to open a connection: " + e); System.err.println("Error while trying to open a connection: " + e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static byte[] convertToByteArray(String input) { public static byte[] convertToByteArray(String input) {
return Client.convertToByteArray(input); return Client.convertToByteArray(input);
} }
public static int getIdFromUsername(String username) { public static int getIdFromUsername(String username) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
if (connection == null) return -1; if (connection == null) return -1;
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
SELECT id SELECT id
FROM accounts FROM accounts
WHERE username = ? WHERE username = ?
""")) { """)) {
statement.setString(1, username); statement.setString(1, username);
ResultSet resultSet = statement.executeQuery(); ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
return resultSet.getInt(1); return resultSet.getInt(1);
} }
return -1; return -1;
} }
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Error while trying to retrieve the id from the username: " + e); System.err.println("Error while trying to retrieve the id from the username: " + e);
return -1; return -1;
} }
} }
public static boolean addMessage(int conversationId, String message) { public static boolean addMessage(int conversationId, String message) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
if (connection == null) return false; if (connection == null) return false;
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
INSERT INTO messages(message, conversation_id, sending_date, sending_time) INSERT INTO messages(message, conversation_id, sending_date, sending_time)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)
""")) { """)) {
statement.setString(1, message); statement.setString(1, message);
statement.setInt(2, conversationId); statement.setInt(2, conversationId);
statement.setDate(3, Date.valueOf(LocalDateTime.now().toLocalDate())); statement.setDate(3, Date.valueOf(LocalDateTime.now().toLocalDate()));
statement.setTime(3, Time.valueOf(LocalDateTime.now().toLocalTime())); statement.setTime(4, Time.valueOf(LocalDateTime.now().toLocalTime()));
int rowsInserted = statement.executeUpdate(); int rowsInserted = statement.executeUpdate();
return rowsInserted == 1; return rowsInserted == 1;
} catch (SQLException ex) { } catch (SQLException ex) {
System.err.println("Error while trying to add a message: " + ex); System.err.println("Error while trying to add a message: " + ex);
return false; return false;
} }
} catch (SQLException ex) { } catch (SQLException ex) {
System.err.println("Error while trying to open a connection: " + ex); System.err.println("Error while trying to open a connection: " + ex);
return false; return false;
} }
} }
public static List<Conversation> getConversations(int sender_id) { public static List<Conversation> getConversations(int sender_id) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
if (connection == null) return null; if (connection == null) return null;
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
SELECT id, sender, recipient SELECT id, sender, recipient
FROM conversations FROM conversations
WHERE sender = ? OR recipient = ? WHERE sender = ? OR recipient = ?
""")) { """)) {
statement.setInt(1, sender_id); statement.setInt(1, sender_id);
statement.setInt(2, sender_id); statement.setInt(2, sender_id);
ResultSet resultSet = statement.executeQuery(); ResultSet resultSet = statement.executeQuery();
List<Conversation> conversations = new ArrayList<>(); List<Conversation> conversations = new ArrayList<>();
while (resultSet.next()) { while (resultSet.next()) {
int id = resultSet.getInt(1); int id = resultSet.getInt(1);
int sender = resultSet.getInt(2); int sender = resultSet.getInt(2);
int recipient = resultSet.getInt(3); int recipient = resultSet.getInt(3);
conversations.add(new Conversation(id, sender, recipient)); conversations.add(new Conversation(id, sender, recipient));
} }
return conversations; return conversations;
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Error while trying to get conversations: " + e); System.err.println("Error while trying to get conversations: " + e);
return null; return null;
} }
} catch (SQLException e) { } catch (SQLException e) {
System.err.println("Error while trying to open a connection: " + e); System.err.println("Error while trying to open a connection: " + e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static boolean addConversation(int conversation_id) { public static boolean addConversation(int sender, int receiver) {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
if (connection == null) return false; if (connection == null) return false;
try (PreparedStatement statement = connection.prepareStatement(""" try (PreparedStatement statement = connection.prepareStatement("""
INSERT INTO conversations(id, sender, recipient) INSERT INTO conversations(sender, recipient)
VALUES (?, ?, ?) VALUES (?, ?)
""")) { """)) {
statement.setInt(1, conversation_id); System.err.println("a");
statement.setInt(1, sender);
int rowsInserted = statement.executeUpdate(); System.err.println("a");
return rowsInserted == 1; statement.setInt(2, receiver);
} catch (SQLException ex) {
System.err.println("Error while trying to add a conversation: " + ex); System.err.println("a");
return false; int rowsInserted = statement.executeUpdate();
} System.err.println("a");
} catch (SQLException ex) { return rowsInserted == 1;
System.err.println("Error while trying to open a connection: " + ex); } catch (SQLException ex) {
return false; System.err.println("Error while trying to add a conversation: " + ex);
} return false;
} }
} catch (SQLException ex) {
public static List<Message> getMessages(int conversation_id) { System.err.println("Error while trying to open a connection: " + ex);
try (Connection connection = getConnection()) { return false;
if (connection == null) return null; }
}
try (PreparedStatement statement = connection.prepareStatement("""
SELECT message, sending_date, sending_time public static int getConversationId(int sender, int receiver) {
FROM messages try (Connection connection = getConnection()) {
WHERE conversation_id = ? if (connection == null) return -1;
""")) {
statement.setInt(1, conversation_id); try (PreparedStatement statement = connection.prepareStatement("""
ResultSet resultSet = statement.executeQuery(); SELECT id
List<Message> messages = new ArrayList<>(); FROM conversations
while (resultSet.next()) { WHERE sender = ? AND recipient = ?
String message = resultSet.getString(1); """)) {
Date sending_date = resultSet.getDate(2); statement.setInt(1, sender);
Time sending_time = resultSet.getTime(3); statement.setInt(2, receiver);
messages.add(new Message(message, sending_date, sending_time)); ResultSet resultSet = statement.executeQuery();
} if (resultSet.next()) {
return messages; return resultSet.getInt(1);
} catch (SQLException e) { }
System.err.println("Error while trying to get messages: " + e); return -1;
return null; } catch (SQLException e) {
} System.err.println("Error while trying to get the conversation id: " + e);
} catch (SQLException e) { return -1;
System.err.println("Error while trying to open a connection: " + e); }
throw new RuntimeException(e); } catch (SQLException e) {
} System.err.println("Error while trying to open a connection: " + e);
} throw new RuntimeException(e);
}
private static Connection getConnection() throws SQLException { }
return DriverManager.getConnection(
System.getenv("db_url"), public static List<Message> getMessages(int conversation_id) {
System.getenv("db_user"), System.getenv("db_pass") try (Connection connection = getConnection()) {
); if (connection == null) return null;
}
} try (PreparedStatement statement = connection.prepareStatement("""
SELECT message, sending_date, sending_time
FROM messages
WHERE conversation_id = ?
""")) {
statement.setInt(1, conversation_id);
ResultSet resultSet = statement.executeQuery();
List<Message> messages = new ArrayList<>();
while (resultSet.next()) {
String message = resultSet.getString(1);
Date sending_date = resultSet.getDate(2);
Time sending_time = resultSet.getTime(3);
messages.add(new Message(message, sending_date, sending_time));
}
return messages;
} catch (SQLException e) {
System.err.println("Error while trying to get messages: " + e);
return null;
}
} catch (SQLException e) {
System.err.println("Error while trying to open a connection: " + e);
throw new RuntimeException(e);
}
}
private static Connection getConnection() throws SQLException {
return DriverManager.getConnection(
"jdbc:mariadb://riefolo.me:3306/chat_rsa",
"proj_sistemi", "$o8a5#diTGg8*Agk"
);
}
}

View File

@ -1,21 +1,22 @@
package controllers; package controllers;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class MessageForwarder { public class MessageForwarder {
private static final Map<Integer, ServerThread> idThread; private static final Map<Integer, ServerThread> idThread;
static { static {
idThread = new HashMap<>(); idThread = new HashMap<>();
} }
public static void addUser(int id, ServerThread thread) { public static void addUser(int id, ServerThread thread) {
idThread.put(id, thread); idThread.put(id, thread);
} }
public static void sendTo(int id, String message, int senderId) throws IOException { public static void sendTo(int id, String message, int senderId) throws IOException {
idThread.get(id).sendMessage(message, senderId); if (idThread.containsKey(id))
} idThread.get(id).sendMessage(message, senderId);
} }
}

View File

@ -1,18 +1,18 @@
package controllers; package controllers;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
public class Server { public class Server {
public static void main(String[] args) { public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(21324)) { try (ServerSocket serverSocket = new ServerSocket(21324)) {
Socket socket = serverSocket.accept(); Socket socket = serverSocket.accept();
ServerThread serverThread = new ServerThread(socket); ServerThread serverThread = new ServerThread(socket);
serverThread.start(); serverThread.start();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }

View File

@ -1,185 +1,190 @@
package controllers; package controllers;
import models.Account; import models.Account;
import models.Rsa; import models.Rsa;
import views.Client; import views.Client;
import java.io.*; import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.Socket; import java.net.Socket;
import java.util.Arrays; import java.util.Arrays;
import static controllers.Database.*; import static controllers.Database.*;
public class ServerThread extends Thread { public class ServerThread extends Thread {
private final Socket client; private final Socket client;
private BufferedReader fromClient; private BufferedReader fromClient;
private BufferedWriter toClient; private BufferedWriter toClient;
private final Rsa rsa; private final Rsa rsa;
private BigInteger clientE, clientN; private BigInteger clientE, clientN;
private int clientId; private int clientId;
public ServerThread (Socket socket) { public ServerThread (Socket socket) {
this.client = socket; this.client = socket;
rsa = new Rsa(1024); rsa = new Rsa(1024);
} }
public void run() { public void run() {
try { try {
fromClient = new BufferedReader(new InputStreamReader(client.getInputStream())); fromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
toClient = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); toClient = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
try { try {
send(rsa.getE().toString()); send(rsa.getE().toString());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
try { try {
send(rsa.getN().toString()); send(rsa.getN().toString());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
try { try {
clientE = new BigInteger(fromClient.readLine()); clientE = new BigInteger(fromClient.readLine());
clientN = new BigInteger(fromClient.readLine()); clientN = new BigInteger(fromClient.readLine());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
for (;;) { for (;;) {
String operation; String operation;
sendEncrypted("Quale operazione vuoi effettuare? (REGISTER|LOGIN): "); sendEncrypted("Quale operazione vuoi effettuare? (REGISTER|LOGIN): ");
try { try {
operation = rsa.decrypt(fromClient.readLine()); operation = rsa.decrypt(fromClient.readLine());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
String username, password; String username, password;
try { try {
sendEncrypted("Inserisci l'username: "); sendEncrypted("Inserisci l'username: ");
username = rsa.decrypt(fromClient.readLine()); username = rsa.decrypt(fromClient.readLine());
sendEncrypted("Inserisci la password: "); sendEncrypted("Inserisci la password: ");
password = rsa.decrypt(fromClient.readLine()); password = rsa.decrypt(fromClient.readLine());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if ("LOGIN".equals(operation)) { if ("LOGIN".equals(operation)) {
if (login(username, password)) { if (login(username, password)) {
Account account = getAccount(username, password); Account account = getAccount(username, password);
if (account == null) { if (account == null) {
sendEncrypted("FAIL"); sendEncrypted("FAIL");
break; break;
} }
sendEncrypted("SUCCESS"); sendEncrypted("SUCCESS");
sendEncrypted(String.valueOf(account.n())); sendEncrypted(String.valueOf(account.n()));
sendEncrypted(String.valueOf(account.e())); sendEncrypted(String.valueOf(account.e()));
sendEncrypted(Arrays.toString(account.d())); sendEncrypted(Arrays.toString(account.d()));
break; break;
} }
} else if ("REGISTER".equals(operation)) { } else if ("REGISTER".equals(operation)) {
if (register(username, password)) { if (register(username, password)) {
sendEncrypted("SUCCESS"); sendEncrypted("SUCCESS");
break; break;
} }
} else { } else {
sendEncrypted("FAIL"); sendEncrypted("FAIL");
} }
} }
MessageForwarder.addUser(clientId, this); MessageForwarder.addUser(clientId, this);
String message,dUsername; String message,dUsername;
sendEncrypted("Inserisci l'username del destinatario: "); sendEncrypted("Inserisci l'username del destinatario: ");
try { try {
dUsername = rsa.decrypt(fromClient.readLine()); dUsername = rsa.decrypt(fromClient.readLine());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
int recipientId = getIdFromUsername(dUsername); int recipientId = getIdFromUsername(dUsername);
Database.addConversation(clientId, recipientId);
for (;;) {
try { for (;;) {
sendEncrypted("Inserisci messaggio: "); try {
message = rsa.decrypt(fromClient.readLine()); sendEncrypted("Inserisci messaggio: ");
} catch (IOException e) { message = fromClient.readLine();
throw new RuntimeException(e); } catch (IOException e) {
} throw new RuntimeException(e);
}
if (message == null || "DISCONNECT".equals(message)) break;
if (message == null || "DISCONNECT".equals(message)) break;
if ("CAMBIA_DESTINATARIO".equals(message)){
try { if ("CAMBIA_DESTINATARIO".equals(message)){
sendEncrypted("Inserisci l'username del nuovo destinatario: "); try {
dUsername = rsa.decrypt(fromClient.readLine()); sendEncrypted("Inserisci l'username del nuovo destinatario: ");
} catch (IOException e) { dUsername = rsa.decrypt(fromClient.readLine());
throw new RuntimeException(e); } catch (IOException e) {
} throw new RuntimeException(e);
recipientId = getIdFromUsername(dUsername); }
continue; recipientId = getIdFromUsername(dUsername);
} Database.addConversation(clientId, recipientId);
continue;
try { }
MessageForwarder.sendTo(recipientId, message, clientId);
} catch (IOException e) { int convId = Database.getConversationId(clientId, recipientId);
throw new RuntimeException(e);
} try {
} MessageForwarder.sendTo(recipientId, message, clientId);
} Database.addMessage(convId, message);
} catch (IOException e) {
private void sendEncrypted(String text) { throw new RuntimeException(e);
try { }
send(rsa.encrypt(text, clientE, clientN)); }
} catch (Exception e) { }
System.err.println(e.getMessage());
} private void sendEncrypted(String text) {
} try {
send(rsa.encrypt(text, clientE, clientN));
public void send(String message) throws IOException { } catch (Exception e) {
toClient.write(message); System.err.println(e.getMessage());
toClient.newLine(); }
toClient.flush(); }
}
public void send(String message) throws IOException {
private boolean login(String username, String password) { toClient.write(message);
Account account = getAccount(username, password); toClient.newLine();
return account != null; toClient.flush();
} }
public boolean register(String username, String password) { private boolean login(String username, String password) {
byte[] clientD; Account account = getAccount(username, password);
return account != null;
try { }
String line = rsa.decrypt(fromClient.readLine());
clientD = convertToByteArray(line); public boolean register(String username, String password) {
} catch (IOException e) { byte[] clientD;
throw new RuntimeException(e);
} try {
String line = rsa.decrypt(fromClient.readLine());
if (!registerAccount(username, password, clientE, Arrays.toString(clientD), clientN)) return false; clientD = convertToByteArray(line);
} catch (IOException e) {
clientId = Database.getIdFromUsername(username); throw new RuntimeException(e);
return clientId != -1; }
}
if (!registerAccount(username, password, clientE, Arrays.toString(clientD), clientN)) return false;
public static byte[] convertToByteArray(String input) {
return Client.convertToByteArray(input); clientId = Database.getIdFromUsername(username);
} return clientId != -1;
}
public void sendMessage(String message, int sender) throws IOException { public static byte[] convertToByteArray(String input) {
send("INCOMING"); return Client.convertToByteArray(input);
send(String.valueOf(sender)); }
send(message);
}
} public void sendMessage(String message, int sender) throws IOException {
send("INCOMING");
send(String.valueOf(sender));
send(message);
}
}

View File

@ -1,73 +1,92 @@
package views; package views;
import models.Rsa; import models.Rsa;
import java.io.*; import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
public class ClientSendThread extends Thread{ import java.util.logging.Logger;
private final BufferedWriter out;
private final BigInteger se,sn; public class ClientSendThread extends Thread{
private final Rsa rsa; private final BufferedWriter out;
private final BufferedReader in; private final BigInteger se,sn;
private final Rsa rsa;
public ClientSendThread(BufferedReader in,BufferedWriter out,BigInteger se, BigInteger sn,Rsa rsa){ private final BufferedReader in;
this.in=in;
this.out = out; public ClientSendThread(BufferedReader in,BufferedWriter out,BigInteger se, BigInteger sn,Rsa rsa){
this.se = se; this.in=in;
this.sn=sn; this.out = out;
this.rsa=rsa; this.se = se;
} this.sn=sn;
this.rsa=rsa;
public void run(){ }
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) { public void run(){
try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine(); while (true) {
System.out.print(rsa.decrypt(s)); try {
s = br.readLine(); String s = in.readLine();
send(rsa.encrypt(s, se, sn)); System.out.print(rsa.decrypt(s));
if("REGISTER".equals(s)){ s = br.readLine();
sendCredentials(br); send(rsa.encrypt(s, se, sn));
try { if("REGISTER".equals(s)){
if (Client.register(s)) break; sendCredentials(br);
} catch (NoSuchAlgorithmException e) { try {
System.err.println("Errore durante la registrazione"); if (Client.register(s)) break;
} } catch (NoSuchAlgorithmException e) {
} System.err.println("Errore durante la registrazione");
else if("LOGIN".equals(s)){ }
sendCredentials(br); }
try { else if("LOGIN".equals(s)){
if (Client.login(s)) break; sendCredentials(br);
} catch (NoSuchAlgorithmException e) { try {
System.err.println("Errore durante l'accesso"); if (Client.login(s)) break;
} } catch (NoSuchAlgorithmException e) {
} System.err.println("Errore durante l'accesso");
} catch (IOException e) { }
throw new RuntimeException(e); }
} } catch (IOException e) {
} throw new RuntimeException(e);
}
ClientReceiveThread crt = new ClientReceiveThread(in,rsa); }
crt.start();
} ClientReceiveThread crt = new ClientReceiveThread(in,rsa);
crt.start();
private void sendCredentials(BufferedReader br) throws IOException {
String s; String s;
s = in.readLine(); try {
System.out.print(rsa.decrypt(s)); s = br.readLine();
s = br.readLine(); send(rsa.encrypt(s, se, sn));
send(rsa.encrypt(s, se, sn)); } catch (IOException ex) {
s = in.readLine(); Logger.getLogger(ClientSendThread.class.getName()).log(Level.SEVERE, null, ex);
System.out.print(rsa.decrypt(s)); }
s = br.readLine();
send(rsa.encrypt(s, se, sn)); while (true) {
} try {
s = br.readLine();
public void send(String message) throws IOException { send(rsa.encrypt(s, se, sn));
out.write(message); } catch (IOException ex) {
out.newLine(); Logger.getLogger(ClientSendThread.class.getName()).log(Level.SEVERE, null, ex);
out.flush(); }
} }
} }
private void sendCredentials(BufferedReader br) throws IOException {
String s;
s = in.readLine();
System.out.print(rsa.decrypt(s));
s = br.readLine();
send(rsa.encrypt(s, se, sn));
s = in.readLine();
System.out.print(rsa.decrypt(s));
s = br.readLine();
send(rsa.encrypt(s, se, sn));
}
public void send(String message) throws IOException {
out.write(message);
out.newLine();
out.flush();
}
}