Commit 845b38d0 by Pedro Cavaleiro

Removed unecessary comments. Fixed SHA256 Checksum for files. Fixed some outputs…

Removed unecessary comments. Fixed SHA256 Checksum for files. Fixed some outputs on the terminal. Added checksum on the encrypted file. Finished task #1. Fixed bug on command input.
parent 2ebb51f1
...@@ -23,10 +23,6 @@ import java.security.Signature; ...@@ -23,10 +23,6 @@ import java.security.Signature;
import java.security.SignatureException; import java.security.SignatureException;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
/**
*
* @author ricar
*/
public class Assinatura { public class Assinatura {
Signature signature; Signature signature;
FileInputStream fIn; FileInputStream fIn;
......
...@@ -3,7 +3,6 @@ package fallintooblivion; ...@@ -3,7 +3,6 @@ package fallintooblivion;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import java.util.Properties;
public class Configs { public class Configs {
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fallintooblivion; package fallintooblivion;
import java.io.File; import java.io.File;
...@@ -171,7 +166,7 @@ public class FallIntoOblivion { ...@@ -171,7 +166,7 @@ public class FallIntoOblivion {
"Fall_Into_Oblivion/Trashed/" + file.getName() + "/" + file.getName() + ".pk"); "Fall_Into_Oblivion/Trashed/" + file.getName() + "/" + file.getName() + ".pk");
// Encrypt the file // Encrypt the file
Helpers.Encryptor.Encrypt(file.getName(), file.getAbsolutePath(), cyphertype); Helpers.Encryptor.Encrypt(file.getName(), file.getAbsolutePath(), cyphertype, hashtype);
// The file was successfully encrypted, we add it to the encrypted list // The file was successfully encrypted, we add it to the encrypted list
encryptedFolders.add(folder.toString()); encryptedFolders.add(folder.toString());
...@@ -215,7 +210,7 @@ public class FallIntoOblivion { ...@@ -215,7 +210,7 @@ public class FallIntoOblivion {
System.out.print("FallIntoOblivion> "); System.out.print("FallIntoOblivion> ");
String choice = ""; String choice = "";
Helpers.CommandsHelper.Commands command = null; Helpers.CommandsHelper.Commands command = Helpers.CommandsHelper.Commands.nocommand;
// We try to read the string // We try to read the string
try { try {
...@@ -298,7 +293,31 @@ public class FallIntoOblivion { ...@@ -298,7 +293,31 @@ public class FallIntoOblivion {
} else { } else {
f = new File(file); f = new File(file);
if (f.exists()) { if (f.exists()) {
// The user has a specific location for this file f = new File(file);
if (f.exists()) {
String signatureFile = file + ".sig";
String publicKeyFile = file + ".pk";
File sf = new File(signatureFile);
File pkf = new File(publicKeyFile);
if (sf.exists() && pkf.exists()) {
try {
boolean valid = digitalSignature.verificarAssinatura(
f.getAbsolutePath(),
sf.getAbsolutePath(),
pkf.getAbsolutePath());
if (valid)
System.out.println("FILE VALIDATOR: The file matches the signature");
else
System.out.println("FILE VALIDATOR: The file does not match the signature");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
} else {
System.out.println("Signature or Public Key files missing\n");
}
} else {
System.out.println("We were unable to find that file\n");
}
} else { } else {
System.out.println("We were unable to find that file\n"); System.out.println("We were unable to find that file\n");
} }
......
...@@ -11,10 +11,7 @@ import java.io.FileOutputStream; ...@@ -11,10 +11,7 @@ import java.io.FileOutputStream;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
/**
*
* @author pedrocavaleiro
*/
public class FolderZiper { public class FolderZiper {
static public void zipFolder(String srcFolder, String destZipFile) throws Exception { static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null; ZipOutputStream zip = null;
......
...@@ -5,15 +5,14 @@ ...@@ -5,15 +5,14 @@
*/ */
package fallintooblivion; package fallintooblivion;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.util.Arrays;
/**
*
* @author pedrocavaleiro
*/
public class Helpers { public class Helpers {
public static class FileHelpers { public static class FileHelpers {
...@@ -140,7 +139,8 @@ public class Helpers { ...@@ -140,7 +139,8 @@ public class Helpers {
sethash, sethash,
setenabled, setenabled,
showconfig, showconfig,
exit exit,
nocommand
} }
/** /**
...@@ -211,11 +211,13 @@ public class Helpers { ...@@ -211,11 +211,13 @@ public class Helpers {
* @param filePath caminho para o ficheiro * @param filePath caminho para o ficheiro
* @param cypher cypher a ser usado * @param cypher cypher a ser usado
*/ */
public static void Encrypt(String fileName, String filePath, String cypher) { public static void Encrypt(String fileName, String filePath, String cypher, String hash) {
try { try {
String outFile = "Fall_Into_Oblivion/Trashed/" + fileName + "/" + fileName; String outFile = "Fall_Into_Oblivion/Trashed/" + fileName + "/" + fileName;
Assinatura fileSigning = new Assinatura();
// TEMPORARY debugging purposes only // TEMPORARY debugging purposes only
// Create the hash of the pin 0000 // Create the hash of the pin 0000
// So far we were only able to use 16 Byte key // So far we were only able to use 16 Byte key
...@@ -236,6 +238,17 @@ public class Helpers { ...@@ -236,6 +238,17 @@ public class Helpers {
break; break;
} }
// Calculates the hash of the encrypted file with the defined hash algorithm
// it defaults to SHA256
switch (hash) {
case "sha256":
Helpers.FileHelpers.writeFile(outFile, ".hash", SHA256.calculateMACBytes(outFile));
break;
default:
Helpers.FileHelpers.writeFile(outFile, ".hash", SHA256.calculateMACBytes(outFile));
break;
}
} catch (Exception ex) { } catch (Exception ex) {
System.out.println(ex.getMessage()); System.out.println(ex.getMessage());
} }
...@@ -247,6 +260,7 @@ public class Helpers { ...@@ -247,6 +260,7 @@ public class Helpers {
* @param file ficheiro para desencriptar * @param file ficheiro para desencriptar
*/ */
public static void Decrypt(String pin, String file) { public static void Decrypt(String pin, String file) {
boolean deleteFiles = true;
try { try {
// Calcular o HASH usando SHA256 do pin e gerar a chave de 16 bytes // Calcular o HASH usando SHA256 do pin e gerar a chave de 16 bytes
...@@ -254,28 +268,49 @@ public class Helpers { ...@@ -254,28 +268,49 @@ public class Helpers {
pinHASH = pinHASH.subSequence(0, 16).toString(); pinHASH = pinHASH.subSequence(0, 16).toString();
// Carregar o ficheiro encriptado para memoria, desencriptar e guardar // Carregar o ficheiro encriptado para memoria, desencriptar e guardar
// TODO: not all files will be aescbc // TODO: not all files will be aescbc
File encFile = new File("Fall_Into_Oblivion/Trashed/" + file + "/" + file + ".aescbc"); File encFile = new File("Fall_Into_Oblivion/Trashed/" + file + "/" + file + ".aescbc");
// Criar a pasta que vai guardar a assinatura e o novo ficheiro // Check if the file is valid
File folder = new File("Fall_Into_Oblivion/Restored/" + file); byte[] checker = SHA256.calculateMACBytes(encFile.getAbsolutePath());
if (!folder.exists()) { byte[] storedHash = Helpers.FileHelpers.readFile(encFile.getAbsolutePath() + ".hash");
folder.mkdir();
} if (Arrays.equals(checker, storedHash)) {
// Criar a pasta que vai guardar a assinatura e o novo ficheiro
File folder = new File("Fall_Into_Oblivion/Restored/" + file);
if (!folder.exists()) {
folder.mkdir();
}
String outFile = "Fall_Into_Oblivion/Restored/" + file + "/" + file;
try {
AES_CBC.copy(Cipher.DECRYPT_MODE, encFile.getAbsolutePath(), outFile,
pinHASH, "0000000000000000");
System.out.println("The file was unlocked!\n" +
"The file is now located in \"Fall_Into_Oblivion/Restored/" + file + "/\"");
} catch (Exception ex) {
System.out.println("The pin " + pin + " is incorrect");
deleteFiles = false;
}
String outFile = "Fall_Into_Oblivion/Restored/" + file + "/" + file; Helpers.FileHelpers.writeFile(outFile, ".sig",
AES_CBC.copy(Cipher.DECRYPT_MODE, encFile.getAbsolutePath(), outFile, Helpers.FileHelpers.readFile("Fall_Into_Oblivion/Trashed/" + file + "/" + file + ".sig"));
pinHASH, "0000000000000000"); Helpers.FileHelpers.writeFile(outFile, ".pk",
Helpers.FileHelpers.readFile("Fall_Into_Oblivion/Trashed/" + file + "/" + file + ".pk"));
Helpers.FileHelpers.writeFile(outFile, ".sig", } else {
Helpers.FileHelpers.readFile("Fall_Into_Oblivion/Trashed/" + file + "/" + file + ".sig")); System.out.println("CRITYCAL ERROR: The file is corrupted!\n");
Helpers.FileHelpers.writeFile(outFile, ".pk", }
Helpers.FileHelpers.readFile("Fall_Into_Oblivion/Trashed/" + file + "/" + file + ".pk"));
File dir = new File("Fall_Into_Oblivion/Trashed/" + file + "/"); if (deleteFiles) {
Helpers.FileHelpers.deleteDirectory(dir); // We do not want corrupted files in the trash, so we delete them
File dir = new File("Fall_Into_Oblivion/Trashed/" + file + "/");
Helpers.FileHelpers.deleteDirectory(dir);
} else {
File dir = new File("Fall_Into_Oblivion/Restored/" + file + "/");
Helpers.FileHelpers.deleteDirectory(dir);
}
} catch (Exception ex) { } catch (Exception ex) {
System.out.println(ex.getMessage()); System.out.println(ex.getMessage());
......
...@@ -23,30 +23,23 @@ public class SHA256 { ...@@ -23,30 +23,23 @@ public class SHA256 {
* Calcular o MAC de um ficheiro usando o algoritmo SHA256 * Calcular o MAC de um ficheiro usando o algoritmo SHA256
* O ficheiro é lido dentro desta função. * O ficheiro é lido dentro desta função.
* Se ocorrer um erro é atirada uma excepção * Se ocorrer um erro é atirada uma excepção
* Antes da função terminar é chamada a função getSHA256Checksum() para *
* converter o checksum the byte[] para String
*
* @param filename a localização do ficheiro * @param filename a localização do ficheiro
* @return checksum em string * @return checksum em bytes
*/ */
public static String calculateMAC(String filename) throws Exception { public static byte[] calculateMACBytes(String filename) throws Exception {
InputStream fileIS = new FileInputStream(filename); MessageDigest md = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream(filename);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
byte[] buffer = new byte[1024]; return mdbytes;
MessageDigest complete = MessageDigest.getInstance("SHA-256");
int numRead;
do {
numRead = fileIS.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fileIS.close();
return getSHA256Checksum(complete.digest());
} }
public static String calculateStringMAC(String text) throws Exception { public static String calculateStringMAC(String text) throws Exception {
......
...@@ -13,10 +13,8 @@ import java.io.*; ...@@ -13,10 +13,8 @@ import java.io.*;
import static java.lang.Thread.sleep; import static java.lang.Thread.sleep;
import java.util.*; import java.util.*;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author Miguel Brandão
*/
public class WatchDir { public class WatchDir {
private final WatchService watcher; private final WatchService watcher;
private final Map<WatchKey,Path> keys; private final Map<WatchKey,Path> keys;
...@@ -85,11 +83,14 @@ public class WatchDir { ...@@ -85,11 +83,14 @@ public class WatchDir {
Path child = dir.resolve(name); Path child = dir.resolve(name);
// print out event // print out event
System.out.format("%s: %s\n", event.kind().name(), child); System.out.println("");
// System.out.format("%s: %s\n", event.kind().name(), child); // Original print
System.out.format("Trashed: %s\n", child);
System.out.print("FallIntoOblivion> ");
foldersToEncryptLock.lock(); foldersToEncryptLock.lock();
try{ try{
foldersToEncrypt.add(child.toString()); foldersToEncrypt.add(child.toString());
System.out.println(foldersToEncrypt.toString()); // System.out.println(foldersToEncrypt.toString());
} finally { } finally {
foldersToEncryptLock.unlock(); foldersToEncryptLock.unlock();
} }
......
...@@ -5,19 +5,37 @@ ...@@ -5,19 +5,37 @@
*/ */
package fallintooblivion; package fallintooblivion;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import static java.lang.System.in; import static java.lang.System.in;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.SignatureException; import java.security.SignatureException;
import java.util.Arrays;
/**
*
* @author ricar
*/
public class functionsDebug { public class functionsDebug {
public static void main(String[] args) { public static void main(String[] args) {
String inFile = "Fall_Into_Oblivion/Trashed/Sem nome.rtf/Sem nome.rtf.aescbc";
String hashFile = "Fall_Into_Oblivion/Trashed/Sem nome.rtf/Sem nome.rtf.aescbc.hash";
File iFile = new File(inFile);
System.out.println("IN FILE: " + iFile.exists());
File hFile = new File(hashFile);
System.out.println("HASH FILE: " + hFile.exists());
try {
byte[] checker = SHA256.calculateMACBytes(inFile);
byte[] hashBytes = Helpers.FileHelpers.readFile(hashFile);
//Helpers.FileHelpers.writeFile(hashFile + "2","", checker);
if (Arrays.equals(checker, hashBytes))
System.out.println("The file is valid");
else
System.out.println("The file is not valid");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
} }
} }
...@@ -7,12 +7,13 @@ The pin must not be outputed to the user nor saved anywere on the computer. ...@@ -7,12 +7,13 @@ The pin must not be outputed to the user nor saved anywere on the computer.
The user, to recover the file, has 3 attempts to guess the pin of the file, if it fails to guess the pin the file gets deleted. The user, to recover the file, has 3 attempts to guess the pin of the file, if it fails to guess the pin the file gets deleted.
The software also checks for errors on the encrypted file upon the decryption process
# Available Cyphers # Available Cyphers
So far there is only one cypher implemented, AES-CBC So far there is only one cypher implemented, AES-CBC
# Available HASH # Available HASH
The hash it's only being used to generate a secure key to encrypt the file, the implemented hash is SHA256 So far there is only on hash algorithm, SHA256 being used to generate the secure key and to create a hash for the encrypted file
# Commands available # Commands available
restorefile restorefile
...@@ -57,7 +58,7 @@ The keysize for now it's allways 16 as there is a problem with java that gives a ...@@ -57,7 +58,7 @@ The keysize for now it's allways 16 as there is a problem with java that gives a
sethash [hash] sethash [hash]
For now only SHA256 is implemented and changing this setting will not have any impact on the software Sets the hash algorithm that will be used to generate the hash of the encrypted file
setenabled [boolean] setenabled [boolean]
...@@ -77,8 +78,6 @@ Terminates the program and all it's threads ...@@ -77,8 +78,6 @@ Terminates the program and all it's threads
# TODO! # TODO!
CHECK FILE FallIntoOblivion.java line 301 (complete if else sequence)
CHECK FILE Helpers.java line 223 (follow instructions in TODO tag) CHECK FILE Helpers.java line 223 (follow instructions in TODO tag)
CHECK FILE Helpers.java line 258 (follow instructions in TODO tag) CHECK FILE Helpers.java line 258 (follow instructions in TODO tag)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment