Encrypt messages with recipient public key

This commit is contained in:
RIEFOLO MARIANO 2024-04-09 10:39:42 +02:00
parent 9265a90300
commit 7778a91e34
4 changed files with 56 additions and 1 deletions

View File

@ -13,6 +13,7 @@ import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import models.PublicKey;
public class Database {
public static boolean registerAccount(String username, String password, BigInteger e, String d, BigInteger n) {
@ -127,6 +128,33 @@ public class Database {
}
}
public static PublicKey getPublicKey(int accountId) {
try (Connection connection = getConnection()) {
if (connection == null) return null;
try (PreparedStatement statement = connection.prepareStatement("""
SELECT e, n
FROM accounts
WHERE id = ?
""")) {
statement.setInt(1, accountId);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
BigInteger e = new BigInteger(resultSet.getString(1));
BigInteger n = new BigInteger(resultSet.getString(2));
return new PublicKey(e, n);
}
return null;
} catch (SQLException e) {
System.err.println("Error while trying to get the public key: " + e);
return null;
}
} catch (SQLException e) {
System.err.println("Error while trying to open a connection: " + e);
throw new RuntimeException(e);
}
}
public static List<Conversation> getConversations(int sender_id) {
try (Connection connection = getConnection()) {
if (connection == null) return null;

View File

@ -10,6 +10,7 @@ import java.net.Socket;
import java.util.Arrays;
import static controllers.Database.*;
import models.PublicKey;
public class ServerThread extends Thread {
private final Socket client;
@ -108,6 +109,9 @@ public class ServerThread extends Thread {
int recipientId = getIdFromUsername(dUsername);
Database.addConversation(clientId, recipientId);
PublicKey pk = Database.getPublicKey(recipientId);
sendEncrypted(pk.e().toString());
sendEncrypted(pk.n().toString());
for (;;) {
try {

View File

@ -0,0 +1,14 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package models;
import java.math.BigInteger;
/**
*
* @author mariano.riefolo
*/
public record PublicKey(BigInteger e, BigInteger n) {
}

View File

@ -62,10 +62,19 @@ public class ClientSendThread extends Thread{
Logger.getLogger(ClientSendThread.class.getName()).log(Level.SEVERE, null, ex);
}
BigInteger recipientE, recipientN;
try {
recipientE = new BigInteger(rsa.decrypt(in.readLine()));
recipientN = new BigInteger(rsa.decrypt(in.readLine()));
} catch (IOException ex) {
Logger.getLogger(ClientSendThread.class.getName()).log(Level.SEVERE, null, ex);
return;
}
while (true) {
try {
s = br.readLine();
send(rsa.encrypt(s, se, sn));
send(rsa.encrypt(s, recipientE, recipientN));
} catch (IOException ex) {
Logger.getLogger(ClientSendThread.class.getName()).log(Level.SEVERE, null, ex);
}