ajouté commentaires descriptifs

This commit is contained in:
m-gues 2021-02-15 23:33:55 +01:00
parent d3adc16146
commit a2a091206b
7 changed files with 70 additions and 741 deletions

View file

@ -39,13 +39,8 @@ public class CommunicationUDP extends Thread {
return tmp; return tmp;
} }
public void setObserver (Observer obs) {
this.observer=obs;
}
public Observer getObserver () { // ----- CHECKERS ----- //
return this.observer;
}
protected boolean containsUserFromID(String id) { protected boolean containsUserFromID(String id) {
for(Utilisateur u : users) { for(Utilisateur u : users) {
@ -67,6 +62,9 @@ public class CommunicationUDP extends Thread {
return false; return false;
} }
// ----- GETTERS ----- //
public int getPortFromPseudo(String pseudo) { public int getPortFromPseudo(String pseudo) {
for(int i=0; i < users.size() ; i++) { for(int i=0; i < users.size() ; i++) {
@ -95,13 +93,30 @@ public class CommunicationUDP extends Thread {
return null; return null;
} }
public Observer getObserver () {
return this.observer;
}
// ----- SETTERS ----- //
public void setObserver (Observer obs) {
this.observer=obs;
}
// ----- USER LIST MANAGEMENT ----- //
//Prints a html table containing the pseudo of all active local users
public void printActiveUsersUDP(PrintWriter out) { public void printActiveUsersUDP(PrintWriter out) {
for (Utilisateur uIn : users) { for (Utilisateur uIn : users) {
out.println("<TH> " + uIn.getPseudo() + ",</TH>"); out.println("<TH> " + uIn.getPseudo() + ",</TH>");
} }
} }
//Add an user to the list of active local users
protected synchronized void addUser(String idClient, String pseudoClient, InetAddress ipClient, int port) throws IOException { protected synchronized void addUser(String idClient, String pseudoClient, InetAddress ipClient, int port) throws IOException {
users.add(new Utilisateur(idClient, pseudoClient, ipClient, port)); users.add(new Utilisateur(idClient, pseudoClient, ipClient, port));
try { try {
@ -111,6 +126,7 @@ public class CommunicationUDP extends Thread {
} }
} }
//Change the pseudo of an user already in the active local users list
protected synchronized void changePseudoUser(String idClient, String pseudoClient, InetAddress ipClient, int port) { protected synchronized void changePseudoUser(String idClient, String pseudoClient, InetAddress ipClient, int port) {
int index = getIndexFromID(idClient); int index = getIndexFromID(idClient);
users.get(index).setPseudo(pseudoClient); users.get(index).setPseudo(pseudoClient);
@ -121,7 +137,7 @@ public class CommunicationUDP extends Thread {
} }
} }
//Remove an user from the active local users list
protected synchronized void removeUser(String idClient, String pseudoClient,InetAddress ipClient, int port) { protected synchronized void removeUser(String idClient, String pseudoClient,InetAddress ipClient, int port) {
int index = getIndexFromID(idClient); int index = getIndexFromID(idClient);
if( index != -1) { if( index != -1) {
@ -134,6 +150,7 @@ public class CommunicationUDP extends Thread {
} }
} }
//Remove all users from the active local users list
public void removeAll(){ public void removeAll(){
int oSize = users.size(); int oSize = users.size();
for(int i=0; i<oSize;i++) { for(int i=0; i<oSize;i++) {
@ -142,6 +159,9 @@ public class CommunicationUDP extends Thread {
} }
// ----- SENDING MESSAGES ----- //
// Send the message "add,id,pseudo" to localhost on all the ports in // Send the message "add,id,pseudo" to localhost on all the ports in
// "portOthers" // "portOthers"
// This allows the receivers' agent (portOthers) to create or modify an entry with the // This allows the receivers' agent (portOthers) to create or modify an entry with the
@ -177,7 +197,7 @@ public class CommunicationUDP extends Thread {
} }
//Broadcast a given message on the local network (here podelized by ports) //Broadcast a given message on the local network (here modelized by ports)
public void sendMessage(Message m) { public void sendMessage(Message m) {
try { try {
for(int port : this.portOthers) { for(int port : this.portOthers) {

View file

@ -15,16 +15,28 @@ public class UDPClient {
private DatagramSocket sockUDP; private DatagramSocket sockUDP;
//private InetAddress broadcast; //private InetAddress broadcast;
/**
* Create an UDP client on the specified port. It will be used to notify the
* other users of this application's user state (Connected/Disconnected/Pseudo
* changed).
*
* @param port
* @throws SocketException
* @throws UnknownHostException
*/
public UDPClient(int port) throws SocketException, UnknownHostException { public UDPClient(int port) throws SocketException, UnknownHostException {
this.sockUDP = new DatagramSocket(port); this.sockUDP = new DatagramSocket(port);
//InetAddress localHost = InetAddress.getLocalHost();
//NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
//this.broadcast = networkInterface.getInterfaceAddresses().get(0).getBroadcast();
} }
//Send a message casted as string to the specified port on localhost /**
* Send a message to the specified port on localhost.
*
* @param message
* @param port
* @throws IOException
*/
protected void sendMessageUDP_local(Message message, int port, InetAddress clientAddress) throws IOException { protected void sendMessageUDP_local(Message message, int port, InetAddress clientAddress) throws IOException {
String messageString= message.toString(); String messageString= message.toString();
DatagramPacket outpacket = new DatagramPacket(messageString.getBytes(), messageString.length(), clientAddress, port); DatagramPacket outpacket = new DatagramPacket(messageString.getBytes(), messageString.length(), clientAddress, port);
@ -32,10 +44,19 @@ public class UDPClient {
} }
// protected void sendMessageUDP_broadcast(String message, int port) throws IOException{ /**
// String messageString=message.toString(); * Send a message to the given address on the specified port.
// DatagramPacket outpacket = new DatagramPacket(messageString.getBytes(), messageString.length(), this.broadcast, port); *
// this.sockUDP.send(outpacket); * @param message
// } * @param port
* @param clientAddress
* @throws IOException
*/
private void sendMessageUDP(Message message, int port, InetAddress clientAddress) throws IOException {
String messageString = message.toString();
DatagramPacket outpacket = new DatagramPacket(messageString.getBytes(), messageString.length(), clientAddress,
port);
this.sockUDP.send(outpacket);
}
} }

View file

@ -16,6 +16,15 @@ public class UDPServer extends Thread {
private CommunicationUDP commUDP; private CommunicationUDP commUDP;
private byte[] buffer; private byte[] buffer;
/**
* Create an UDP Server on the specified port. It will be used to read the
* other users states (Connected/Disconnected/Pseudo).
*
* @param port
* @param commUDP
* @throws SocketException
*/
public UDPServer(int port, CommunicationUDP commUDP) throws SocketException { public UDPServer(int port, CommunicationUDP commUDP) throws SocketException {
this.commUDP = commUDP; this.commUDP = commUDP;
this.sockUDP = new DatagramSocket(port); this.sockUDP = new DatagramSocket(port);

View file

@ -1,73 +0,0 @@
package database;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
class SQLiteCreateTables {
protected static void createTableUser(Connection connec) throws SQLException {
String createTableUser = "CREATE TABLE IF NOT EXISTS user (\r\n"
+ " id INTEGER PRIMARY KEY AUTOINCREMENT,\r\n"
+ " username VARCHAR (50) NOT NULL\r\n"
+ " UNIQUE ON CONFLICT ROLLBACK,\r\n"
+ " pwd_salt BLOB,\r\n"
+ " db_datakey_salt BLOB,\r\n"
+ " encrypted_pwd_hashsalt BLOB,\r\n"
+ " encrypted_db_datakey BLOB,\r\n"
+ " iv_datakey BLOB\r\n"
+ ");";
Statement stmt = connec.createStatement();
stmt.execute(createTableUser);
}
protected static void createTableConversation(Connection connec) throws SQLException {
String createTableConversation = "CREATE TABLE IF NOT EXISTS conversation (\r\n"
+ " id_conversation INTEGER PRIMARY KEY AUTOINCREMENT,\r\n"
+ " id_emetteur INTEGER REFERENCES user (id) \r\n"
+ " NOT NULL,\r\n"
+ " id_recepteur INTEGER REFERENCES user (id) \r\n"
+ " NOT NULL,\r\n"
+" iv_conversation BLOB NOT NULL"
+ ");";
Statement stmt = connec.createStatement();
stmt.execute(createTableConversation);
}
protected static void createTableMessage(Connection connec) throws SQLException {
String createTableMessage = "CREATE TABLE IF NOT EXISTS message (\r\n"
+ " id_message INTEGER PRIMARY KEY AUTOINCREMENT,\r\n"
+ " id_conversation INTEGER REFERENCES conversation (id_conversation) \r\n"
+ " NOT NULL,\r\n"
+ " id_type INTEGER REFERENCES type (id_type) \r\n"
+ " NOT NULL,\r\n"
+ " content BLOB,\r\n"
+ " date INTEGER NOT NULL,\r\n"
+ " extension VARCHAR (20) \r\n"
+ ");\r\n";
Statement stmt = connec.createStatement();
stmt.execute(createTableMessage);
}
protected static void createTableType(Connection connec) throws SQLException {
String createTableType = "CREATE TABLE IF NOT EXISTS type (\r\n" + " id_type INTEGER PRIMARY KEY,\r\n"
+ " label VARCHAR (20) NOT NULL\r\n" + ");";
Statement stmt = connec.createStatement();
stmt.execute(createTableType);
String typeText = "INSERT OR IGNORE INTO type (id_type, label) " + "VALUES (0, 'text');";
String typeFile = "INSERT OR IGNORE INTO type (id_type, label) " + "VALUES (1, 'file');";
String typeImage = "INSERT OR IGNORE INTO type (id_type, label) " + "VALUES (2, 'image');";
stmt.execute(typeText);
stmt.execute(typeFile);
stmt.execute(typeImage);
}
}

View file

@ -1,84 +0,0 @@
package database;
import java.util.Base64;
import java.util.Random;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
class SQLiteEncprytion {
private static final Random RANDOM = new SecureRandom();
private static final int ITERATIONS = 10000;
private static final int KEY_LENGTH = 256;
protected static final String encryptAlgorithm = "AES/CBC/PKCS5Padding";
protected static byte[] getNextSalt() {
byte[] salt = new byte[24];
RANDOM.nextBytes(salt);
return salt;
}
protected static byte[] hash(char[] password, byte[] salt) {
return SQLiteEncprytion.getKey(password, salt).getEncoded();
}
protected static SecretKey getKey(char[] password, byte[] salt) {
PBEKeySpec saltpwd = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = skf.generateSecret(saltpwd);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");
return key;
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
saltpwd.clearPassword();
}
return null;
}
public static IvParameterSpec generateIv() {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
return new IvParameterSpec(iv);
}
protected static byte[] encrypt(String algorithm, byte[] input, SecretKey key, IvParameterSpec iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] cipherText = cipher.doFinal(input);
return Base64.getEncoder().encode(cipherText);
}
protected static byte[] decryptByte(String algorithm, byte[] cipherText, SecretKey key, IvParameterSpec iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return plainText;
}
protected static String decryptString(String algorithm, byte[] cipherText, SecretKey key, IvParameterSpec iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return new String(SQLiteEncprytion.decryptByte(algorithm, cipherText, key, iv) );
}
public static byte[] keyToByte(SecretKey key) {
return Base64.getEncoder().encode(key.getEncoded());
}
public static SecretKey byteToKey(byte[] encodedKey) {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
}
}

View file

@ -1,563 +0,0 @@
package database;
import java.io.File;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import main.Utilisateur;
import messages.MauvaisTypeMessageException;
import messages.Message;
import messages.MessageTexte;
import messages.Message.TypeMessage;
import messages.MessageFichier;
public class SQLiteManager {
private static final String DATABASE_RELATIVE_PATH = "../database";
public static String[] hardcodedNames = {"Olivia","Liam","Benjamin","Sophia","Charlotte","Noah","Elijah","Isabella",
"Oliver","Emma","William","Amelia","Evelyn","James","Mia","Ava","Lucas","Mason","Ethan","Harper"};
private Connection connec;
private int numDatabase;
private SecretKey dbDataKey;
public SQLiteManager(int numDatabase) {
this.numDatabase = numDatabase;
this.openConnection();
try {
SQLiteCreateTables.createTableUser(this.connec);
SQLiteCreateTables.createTableConversation(this.connec);
SQLiteCreateTables.createTableType(this.connec);
SQLiteCreateTables.createTableMessage(this.connec);
} catch (SQLException e) {
this.closeConnection();
File db = new File("../database"+this.numDatabase+".db");
if(db.delete()) {
System.out.println("supp");
}else {
System.out.println("no supp");
}
e.printStackTrace();
}
this.closeConnection();
}
private void openConnection() {
String url = "jdbc:sqlite:"+ DATABASE_RELATIVE_PATH + this.numDatabase + ".db";
try {
//Class.forName("org.sqlite.JDBC");
this.connec = DriverManager.getConnection(url);
System.out.println("Connection to bdd established");
} catch (SQLException /*| ClassNotFoundException*/ e) {
System.out.println(e.getMessage());
}
}
private void closeConnection() {
try {
if (this.connec != null) {
this.connec.close();
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public int insertAllMessages(ArrayList<Message> messages, String usernameSender, String usernameReceiver) throws SQLException{
int nbRows = 0;
this.openConnection();
int idSender = this.getIDUser(usernameSender);
int idReceiver = this.getIDUser(usernameReceiver);
if(idSender == -1) {
this.insertUser(usernameSender);
idSender = this.getIDUser(usernameSender);
}
if(idReceiver == -1) {
this.insertUser(usernameReceiver);
idReceiver = this.getIDUser(usernameReceiver);
}
int idConversation = getIDConversation(idSender, idReceiver);
if(idConversation == -1) {
this.insertConversation(idSender, idReceiver);
idConversation = getIDConversation(idSender, idReceiver);
}
IvParameterSpec ivConversation = this.getIvConversation(idConversation);
this.connec.setAutoCommit(false);
for(Message m : messages) {
try {
nbRows += this.insertMessage(idConversation, m, ivConversation);
} catch (SQLException e) {
e.printStackTrace();
this.connec.rollback();
}
}
this.connec.commit();
this.closeConnection();
//System.out.println("Nombre de message(s) insérée(s) : " + nbRows);
return nbRows;
}
public ArrayList<Message> getHistoriquesMessages(String usernameOther, String pseudoOther) throws SQLException {
this.openConnection();
ArrayList<Message> messages = new ArrayList<Message>();
String usernameSelf = Utilisateur.getSelf().getId();
int idSelf = this.getIDUser(usernameSelf);
int idOther = this.getIDUser(usernameOther);
int idConversationSelf = this.getIDConversation(idSelf, idOther);
int idConversationOther = this.getIDConversation(idOther, idSelf);
IvParameterSpec ivConversation = this.getIvConversation(idConversationSelf);
// String str = "datetime(d1,'unixepoch','localtime')";
String getHistoriqueRequest = "SELECT id_conversation, id_type, content, date, extension "
+ "FROM message "
+ "WHERE id_conversation IN (?,?) "
+ "ORDER by date";
PreparedStatement prepStmt = this.connec.prepareStatement(getHistoriqueRequest);
prepStmt.setInt(1, idConversationSelf);
prepStmt.setInt(2, idConversationOther);
ResultSet res = prepStmt.executeQuery();
//Retrieve the messages one by one
//Create the appropriate message object depending on the type and sender/receiver
//and add the message in the list
while(res.next()) {
int idType = res.getInt("id_type");
String type = this.getType(idType);
String content = null;
try {
content = this.bytesToStringContent(res.getBytes("content"), ivConversation);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException
| SQLException e1) {
//System.out.println("erreur déchiffrement");
}
Message message = null;
String extension;
if(!type.equals("")) {
try {
switch(type) {
case "text":
message = new MessageTexte(TypeMessage.TEXTE, content);
break;
case "file":
extension = res.getString("extension");
message = new MessageFichier(TypeMessage.FICHIER, content, extension);
break;
default:
extension = res.getString("extension");
message = new MessageFichier(TypeMessage.IMAGE, content, extension);
}
} catch (MauvaisTypeMessageException e) {
e.printStackTrace();
}
}
if(res.getInt("id_conversation") == idConversationSelf) {
message.setSender("Moi");
}else{
message.setSender(pseudoOther);
}
message.setDateMessage(res.getString("date"));
if(content != null) {
messages.add(message);
}
}
this.closeConnection();
return messages;
}
private void insertUser(String username) throws SQLException {
String insertUserRequest = "INSERT INTO user (username) " + "VALUES (?);";
PreparedStatement prepStmt = this.connec.prepareStatement(insertUserRequest);
prepStmt.setString(1, username);
prepStmt.executeUpdate();
}
public int getIDUser(String username) throws SQLException {
String getIDRequest = "SELECT id " + " FROM user" + " WHERE username = ? ;";
PreparedStatement prepStmt = this.connec.prepareStatement(getIDRequest);
prepStmt.setString(1, username);
ResultSet res = prepStmt.executeQuery();
if (res.next()) {
return res.getInt("id");
}
return -1;
}
private void insertConversation(int idSender, int idReceiver) throws SQLException {
String insertConversationRequest = "INSERT INTO conversation (id_emetteur, id_recepteur, iv_conversation) " + "VALUES "
+ "(?, ?, ?),"
+ "(?, ?, ?);";
byte[] ivConversation = SQLiteEncprytion.generateIv().getIV();
PreparedStatement prepStmt = this.connec.prepareStatement(insertConversationRequest);
prepStmt.setInt(1, idSender);
prepStmt.setInt(2, idReceiver);
prepStmt.setBytes(3, ivConversation);
prepStmt.setInt(4, idReceiver);
prepStmt.setInt(5, idSender);
prepStmt.setBytes(6, ivConversation);
prepStmt.executeUpdate();
}
private int getIDConversation(int idSender, int idReceiver) throws SQLException {
String getIDRequest = "SELECT id_conversation " + "FROM conversation " + "WHERE id_emetteur = ? "
+ "AND id_recepteur = ? ;";
PreparedStatement prepStmt = this.connec.prepareStatement(getIDRequest);
prepStmt.setInt(1, idSender);
prepStmt.setInt(2, idReceiver);
ResultSet res = prepStmt.executeQuery();
if (res.next()) {
return res.getInt("id_conversation");
}
return -1;
}
private IvParameterSpec getIvConversation(int idConversation) throws SQLException {
String getIvRequest = "SELECT iv_conversation " + "FROM conversation " + "WHERE id_conversation = ?;";
PreparedStatement prepStmt = this.connec.prepareStatement(getIvRequest);
prepStmt.setInt(1, idConversation);
ResultSet res = prepStmt.executeQuery();
if (res.next()) {
return new IvParameterSpec(res.getBytes("iv_conversation"));
}
return null;
}
private int getIDType(String label) throws SQLException {
String getIDRequest = "SELECT id_type FROM type WHERE label = ?;";
PreparedStatement prepStmt = this.connec.prepareStatement(getIDRequest);
prepStmt.setString(1, label);
ResultSet res = prepStmt.executeQuery();
if (res.next()) {
return res.getInt("id_type");
}
return -1;
}
private String getType(int idType) throws SQLException {
String getTypeRequest = "SELECT label FROM type WHERE id_type = ?;";
PreparedStatement prepStmt = this.connec.prepareStatement(getTypeRequest);
prepStmt.setInt(1, idType);
ResultSet res = prepStmt.executeQuery();
if(res.next()) {
return res.getString("label");
}
return "";
}
private byte[] stringToBytesContent(Message m, IvParameterSpec iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
String content;
if (m.getTypeMessage() == TypeMessage.TEXTE) {
MessageTexte messageTxt = (MessageTexte) m;
content = messageTxt.getContenu();
}else {
MessageFichier messageFichier = (MessageFichier) m;
content = messageFichier.getContenu();
}
byte[] encryptedContent = SQLiteEncprytion.encrypt(SQLiteEncprytion.encryptAlgorithm, content.getBytes(), this.dbDataKey, iv);
return encryptedContent;
}
private String bytesToStringContent(byte[] encryptedContent, IvParameterSpec iv) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return SQLiteEncprytion.decryptString(SQLiteEncprytion.encryptAlgorithm, encryptedContent, this.dbDataKey, iv);
}
private String processMessageType(Message m) {
switch (m.getTypeMessage()) {
case TEXTE: return "text";
case FICHIER: return "file";
case IMAGE: return "image";
default: return "";
}
}
private String processExtension(Message m) {
if(m.getTypeMessage() == TypeMessage.TEXTE) {
return null;
}else {
MessageFichier mFile = (MessageFichier) m;
return mFile.getExtension();
}
}
private int insertMessage(int idConversation, Message m, IvParameterSpec iv) throws SQLException {
String dateMessage = m.getDateMessage();
String extension = this.processExtension(m);
String type = this.processMessageType(m);
int idType = this.getIDType(type);
byte[] content = null;
try {
content = this.stringToBytesContent(m, iv);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
String insertMessageRequest = "INSERT INTO message(id_conversation, id_type, content, date, extension) "
+ "VALUES (?, ?, ?, ?, ?);";
PreparedStatement prepStmt = this.connec.prepareStatement(insertMessageRequest);
prepStmt.setInt(1, idConversation);
prepStmt.setInt(2, idType);
prepStmt.setBytes(3, content);
prepStmt.setString(4, dateMessage);
prepStmt.setString(5, extension);
int nbRows = prepStmt.executeUpdate();
return nbRows;
}
public void createNewUserEncrypt(String username, String password) {
String algo = SQLiteEncprytion.encryptAlgorithm;
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] passwordSalt = SQLiteEncprytion.getNextSalt();
byte[] dbDataKeySalt = SQLiteEncprytion.getNextSalt();
SecretKey dbDataKey = keyGen.generateKey();
SecretKey dbDataEncryptKey = SQLiteEncprytion.getKey(password.toCharArray(), dbDataKeySalt);
IvParameterSpec ivDbDataKey = SQLiteEncprytion.generateIv();
byte[] passwordHash = SQLiteEncprytion.hash(password.toCharArray(), passwordSalt);
byte[] dbDataKeyEncrypted = null;
byte[] encryptedPasswordHash = null;
try {
dbDataKeyEncrypted = SQLiteEncprytion.encrypt(
algo, SQLiteEncprytion.keyToByte(dbDataKey), dbDataEncryptKey, ivDbDataKey);
encryptedPasswordHash = SQLiteEncprytion.encrypt(
algo, passwordHash , dbDataKey, ivDbDataKey);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.openConnection();
String createUserRequest = "INSERT INTO user(username, pwd_salt, db_datakey_salt, encrypted_pwd_hashsalt, encrypted_db_datakey, iv_datakey) "
+ "VALUES (?, ?, ?, ?, ?, ?); ";
PreparedStatement prepStmt = null;
try {
prepStmt = this.connec.prepareStatement(createUserRequest);
prepStmt.setString(1, username);
prepStmt.setBytes(2, passwordSalt);
prepStmt.setBytes(3, dbDataKeySalt);
prepStmt.setBytes(4, encryptedPasswordHash);
prepStmt.setBytes(5, dbDataKeyEncrypted);
prepStmt.setBytes(6, ivDbDataKey.getIV());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
prepStmt.executeUpdate();
System.out.println("Utilisateur crée");
} catch (SQLException e) {
System.out.println("Nom d'utilisateur déjà pris");
}
this.closeConnection();
}
/**
*
* @param username
* @param password
* @return -1 if user do not exists,
* 0 if password incorrect,
* 1 if password correct
* @throws SQLException
*/
public int checkPwd(String username, char[] password) throws SQLException {
this.openConnection();
String selectUserDataRequest = "SELECT pwd_salt, db_datakey_salt, encrypted_pwd_hashsalt, encrypted_db_datakey, iv_datakey "
+ "FROM user "
+ "WHERE username = ?;";
PreparedStatement prepStmt;
prepStmt = this.connec.prepareStatement(selectUserDataRequest);
prepStmt.setString(1, username);
ResultSet res = prepStmt.executeQuery();
if(!res.next()) {
return -1;
}
byte[] passwordSalt = res.getBytes("pwd_salt");
byte[] dbDataKeySalt = res.getBytes("db_datakey_salt");
SecretKey dbDataEncryptKey = SQLiteEncprytion.getKey(password, dbDataKeySalt);
IvParameterSpec iv = new IvParameterSpec(res.getBytes("iv_datakey"));
byte[] encryptedDbDataKey = res.getBytes("encrypted_db_datakey");
SecretKey dbDataKey = null;
try {
dbDataKey = SQLiteEncprytion.byteToKey(
SQLiteEncprytion.decryptByte(SQLiteEncprytion.encryptAlgorithm, encryptedDbDataKey, dbDataEncryptKey, iv)
);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
//System.out.println("Problème déchiffrement clé db");
}
this.dbDataKey = dbDataKey;
byte[] encryptedPasswordHash = res.getBytes("encrypted_pwd_hashsalt");
byte[] passwordHash = SQLiteEncprytion.hash(password, passwordSalt);
this.closeConnection();
boolean checkHash = this.checkHashPwd(passwordHash ,encryptedPasswordHash, dbDataKey, iv);
if(checkHash) {
return 1;
}
return 0;
}
private boolean checkHashPwd(byte[] passwordHash, byte[] encryptedPasswordHash, SecretKey dbDataKey, IvParameterSpec iv) {
byte[] expectedHash = "".getBytes();
try {
expectedHash = SQLiteEncprytion.decryptByte(SQLiteEncprytion.encryptAlgorithm, encryptedPasswordHash, dbDataKey, iv);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
}
if (passwordHash.length != expectedHash.length) return false;
for (int i = 0; i < passwordHash.length; i++) {
if (passwordHash[i] != expectedHash[i]) return false;
}
return true;
}
public static void main(String[] args) {
String[] hardcodedNames = {"Olivia","Liam","Benjamin","Sophia","Charlotte","Noah","Elijah","Isabella",
"Oliver","Emma","William","Amelia","Evelyn","James","Mia","Ava","Lucas","Mason","Ethan","Harper"};
String pwdPrefix = "aze1$";
SQLiteManager sqlManager = new SQLiteManager(0);
for(int i=0; i<hardcodedNames.length; i++) {
sqlManager.createNewUserEncrypt(hardcodedNames[i]+i, pwdPrefix+hardcodedNames[i].charAt(0)+i);
}
}
}

View file

@ -21,7 +21,6 @@ import messages.*;
*/ */
@WebServlet("/ServletPresence") @WebServlet("/ServletPresence")
//Faire un publish (get) séparé en utilisant les cookies pour stocker les modifications : pose problème au niveau de la synchro des pseudos
public class ServletPresence extends HttpServlet implements Observer { public class ServletPresence extends HttpServlet implements Observer {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -135,7 +134,7 @@ public class ServletPresence extends HttpServlet implements Observer {
out.println( "</HTML>" ); out.println( "</HTML>" );
} }
//Affiche un message d'erreur en cas de requête invalide //Affiche un message d'erreur en cas d'id inconnue
private void printErrorUnkwownUser(PrintWriter out) { private void printErrorUnkwownUser(PrintWriter out) {
out.println( "<HTML>" ); out.println( "<HTML>" );
out.println( "<HEAD>"); out.println( "<HEAD>");