From 64bd355c3d694ed0f87e6e20362dfe459c020a93 Mon Sep 17 00:00:00 2001
From: yschl <ys037@hdm-stuttgart.de>
Date: Sat, 6 Jan 2024 18:23:23 +0100
Subject: [PATCH] Update: Code for working encryption while not interfering
 with already encrypted code in CryptoUtils.java Add: CryptoUtilsTest.java
 (Added UnitTests for CryptoUtils.java Class) Add: files for
 UnitTestsencryptedtestFile

---
 .../Classes/Utilities/CryptoUtils.java        | 114 +++++++++++++++---
 ...encrypted;encryptiondecryptiontestFile.txt |   1 +
 .../database/encryptiondecryptiontestFile.txt |   1 +
 .../Classes/Utilities/CryptoUtilsTest.java    |  51 ++++++++
 4 files changed, 150 insertions(+), 17 deletions(-)
 create mode 100644 src/main/resources/database/encrypted;encryptiondecryptiontestFile.txt
 create mode 100644 src/main/resources/database/encryptiondecryptiontestFile.txt
 create mode 100644 src/test/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtilsTest.java

diff --git a/src/main/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtils.java b/src/main/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtils.java
index f2deb236..e2e1cab6 100644
--- a/src/main/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtils.java
+++ b/src/main/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtils.java
@@ -1,10 +1,9 @@
 package de.hdm_stuttgart.battlearena.Model.DataStorage.Classes.Utilities;
 import de.hdm_stuttgart.battlearena.Model.DataStorage.Classes.Exceptions.CryptoException;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
+import java.io.*;
 import java.security.InvalidKeyException;
 import java.security.Key;
 import java.security.NoSuchAlgorithmException;
@@ -16,6 +15,9 @@ import javax.crypto.NoSuchPaddingException;
 import javax.crypto.spec.SecretKeySpec;
 
 import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
 
 public class CryptoUtils{
@@ -23,19 +25,26 @@ public class CryptoUtils{
     private static final String ALGORITHM = "AES";
     private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
     private static String key = "Peters Olivenöl";
+    private static String  encrypted_as_word = "encrypted;";
+    private static boolean alreadyencrypted = false;
+    private static final Logger log = LogManager.getLogger(CryptoUtils.class);
 
-    public static void encrypt(File inputFile)
-            throws CryptoException {
-        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile);
+
+    public static void encrypt(File inputFile) throws CryptoException {
+        alreadyencrypted = check_if_file_already_encrypted(inputFile);        //Yet to implement
+        if(alreadyencrypted == false){
+            doCrypto(Cipher.ENCRYPT_MODE, key, inputFile);
+        }else {
+            log.info("This file is already encrypted and doesnt need to be encrypted anymore! " + inputFile);
+        }
     }
 
-    public static String[] decrypt(File inputFile)
-            throws CryptoException {
+    public static String[] decrypt(File inputFile) throws CryptoException {
         doCrypto(Cipher.DECRYPT_MODE, key, inputFile);
         return parts;
     }
 
-    public static String[] doCrypto(int cipherMode, String key, File inputFile) throws CryptoException {
+    private static String[] doCrypto(int cipherMode, String key, File inputFile) throws CryptoException {
         try {
             Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
             Cipher cipher = Cipher.getInstance(TRANSFORMATION);
@@ -43,20 +52,91 @@ public class CryptoUtils{
 
             FileInputStream inputStream = new FileInputStream(inputFile);
             byte[] inputBytes = new byte[(int) inputFile.length()];
-            inputStream.read(inputBytes);
+            inputStream.read(inputBytes);   //liest from inputstream into BufferArray
 
             byte[] outputBytes = cipher.doFinal(inputBytes);
 
             String completeString = new String(outputBytes, StandardCharsets.UTF_8);
-            //System.out.println(completeString);
+            //log.info("completeString/outputBytes: " + completeString);
             parts = completeString.split(";");
 
-            if(cipherMode == Cipher.ENCRYPT_MODE){
-                FileOutputStream outputStream = new FileOutputStream(inputFile);
-                outputStream.write(outputBytes);
+                if(cipherMode == Cipher.ENCRYPT_MODE){
+                    FileOutputStream outputStream = new FileOutputStream(inputFile);
+                    outputStream.write(outputBytes);//outputBytes
+                    outputStream.close();
+                }
+            inputStream.close();
 
-                outputStream.close();
+        } catch (NoSuchPaddingException | NoSuchAlgorithmException
+                 | InvalidKeyException | BadPaddingException
+                 | IllegalBlockSizeException | IOException ex) {
+            throw new CryptoException("Error encrypting/decrypting file", ex);
+        }
+        return parts;
+    }
+    public static boolean check_if_file_already_encrypted(File inputFile){
+        String filename =  inputFile.getName();
+        //log.info("filename: " + filename);
+            if(filename.contains(encrypted_as_word)){
+                return alreadyencrypted =true;
             }
+        inputFile.renameTo(new File("src\\main\\resources\\database\\" + encrypted_as_word + filename));
+        return alreadyencrypted = false;
+    }
+
+       /*public static String[] doCrypto(int cipherMode, String key, File inputFile) throws CryptoException {
+        try {
+
+            String filename = inputFile.getName();
+            //String encrypted_as_word = "encrypted;";
+            byte[] encryptet_as_word_as_bytes = encrypted_as_word.getBytes();
+
+            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
+            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
+            cipher.init(cipherMode, secretKey);
+
+            FileInputStream inputStream = new FileInputStream(inputFile);
+            byte[] inputBytes = new byte[(int) inputFile.length()];
+            inputStream.read(inputBytes);   //liest from inputstream into BufferArray
+
+            String inputbytes = new String(inputBytes, StandardCharsets.UTF_8);
+            String[] wellencrypted = inputbytes.split(";");
+
+            log.info("encrypted_as_word.substring(0,encrypted_as_word.length()-1): " + encrypted_as_word.substring(0,encrypted_as_word.length()-1));
+
+            if(wellencrypted[0].equals(encrypted_as_word.substring(0,encrypted_as_word.length()-1))){
+                wellencrypted = Arrays.copyOfRange(wellencrypted,1,wellencrypted.length);
+                inputBytes = wellencrypted[0].getBytes();
+                log.info("Das Wort encrypted ist enthalten!");
+                log.info("inputBytes: " + new String(inputBytes, StandardCharsets.UTF_8));
+
+            }
+            log.info("wellencrypted[0]: " +wellencrypted[0]);
+            log.info("wel[0]: " + wel[0]);
+             log.info("inputbytes: " + inputbytes);
+            log.info("inputBytes: " + new String(inputBytes, StandardCharsets.UTF_8));
+
+            byte[] outputBytes = cipher.doFinal(inputBytes);
+
+
+            String completeString = new String(outputBytes, StandardCharsets.UTF_8);
+            log.info("completeString/outputBytes: " + completeString);
+            parts = completeString.split(";");
+
+                if(cipherMode == Cipher.ENCRYPT_MODE){
+                    FileOutputStream outputStream = new FileOutputStream(inputFile);
+                    ByteArrayOutputStream outputStream12 = new ByteArrayOutputStream( );
+                    outputStream12.write(encryptet_as_word_as_bytes);
+                    outputStream12.write(outputBytes);
+                    byte combined[] = outputStream12.toByteArray( );
+                    String combinedbytes = new String(combined, StandardCharsets.UTF_8);
+                    log.info("combined: " + combinedbytes);
+
+
+                    outputStream.write(combined);//outputBytes
+
+                    outputStream.close();
+                }
 
             inputStream.close();
 
@@ -66,5 +146,5 @@ public class CryptoUtils{
             throw new CryptoException("Error encrypting/decrypting file", ex);
         }
         return parts;
-    }
+    }*/
 }
diff --git a/src/main/resources/database/encrypted;encryptiondecryptiontestFile.txt b/src/main/resources/database/encrypted;encryptiondecryptiontestFile.txt
new file mode 100644
index 00000000..575b3c72
--- /dev/null
+++ b/src/main/resources/database/encrypted;encryptiondecryptiontestFile.txt
@@ -0,0 +1 @@
+Hier steht ein Testtext.
\ No newline at end of file
diff --git a/src/main/resources/database/encryptiondecryptiontestFile.txt b/src/main/resources/database/encryptiondecryptiontestFile.txt
new file mode 100644
index 00000000..4b7d67bb
--- /dev/null
+++ b/src/main/resources/database/encryptiondecryptiontestFile.txt
@@ -0,0 +1 @@
+èkæÝ9z"²œÓF'ÙøŒ­®[4]ÙqŠð(/
\ No newline at end of file
diff --git a/src/test/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtilsTest.java b/src/test/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtilsTest.java
new file mode 100644
index 00000000..37ac3969
--- /dev/null
+++ b/src/test/java/de/hdm_stuttgart/battlearena/Model/DataStorage/Classes/Utilities/CryptoUtilsTest.java
@@ -0,0 +1,51 @@
+package de.hdm_stuttgart.battlearena.Model.DataStorage.Classes.Utilities;
+
+//import de.hdm_stuttgart.battlearena.Model.DataStorage.Classes.Exceptions.CryptoException;
+
+import de.hdm_stuttgart.battlearena.Model.DataStorage.Classes.Exceptions.CryptoException;
+import org.junit.jupiter.api.Test;
+
+import java.io.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class CryptoUtilsTest {
+    private static File encryptiondecryptiontestFile = new File("src\\main\\resources\\database\\encryptiondecryptiontestFile.txt");
+    private static File encryptedtestFile = new File("src\\main\\resources\\database\\encrypted;encryptedtestFile.txt");
+    private static boolean alreadyencrypted;
+
+    @Test
+    void encrypt_decryptiontest() throws IOException {
+        String text="";
+        String[] parts;
+        String testtext = "Hier steht ein Testtext.";
+
+        BufferedWriter writer = new BufferedWriter(new FileWriter(encryptiondecryptiontestFile));
+        writer.write(testtext);
+        writer.close();
+        try {
+            CryptoUtils.encrypt(encryptiondecryptiontestFile);
+            parts = CryptoUtils.decrypt(encryptiondecryptiontestFile);
+            text = parts[0];
+            System.out.println(text);
+        } catch (CryptoException ex) {
+            System.out.println(ex.getMessage());
+            ex.printStackTrace();
+        }
+        assertEquals(testtext,text);
+    }
+    @Test
+    void check_if_file_already_encrypted(){
+        alreadyencrypted = CryptoUtils.check_if_file_already_encrypted(encryptedtestFile);
+        assertTrue(alreadyencrypted);
+    }
+    @Test
+    void check_if_file_not_yet_encrypted(){
+        alreadyencrypted = CryptoUtils.check_if_file_already_encrypted(encryptiondecryptiontestFile);
+        assertFalse(alreadyencrypted);
+    }
+    @Test
+    void checkCryptoexception(){
+        //
+    }
+}
-- 
GitLab