Как я могу улучшить этот код? Также мне было интересно, почему каждый раз, когда я запускаю этот кусок кода, содержимое файла всегда перезаписывается? - PullRequest
0 голосов
/ 27 января 2020
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;

public class Main {
//This function will decode the value of the XOR binary back
  public static void decodingXorCipher(String[] XorApplied) throws IOException
  {
    String binaryValue ; 
    char cTemp; 
    String szOutput = ""; 
    System.out.println("Converting Binary to ASCII Text...") ;
    for(int q = 0 ; q < XorApplied.length ; q++)
    {
      binaryValue = XorApplied[q] ; 
      //This is the method that has converted binary back into ASCII text
      cTemp = (binaryToChar(binaryValue)); 
      szOutput = szOutput + cTemp ; 
    }
    //Stores the encrypted message to a file
    System.out.println(szOutput) ; 
    PrintWriter writer = new PrintWriter("eMessage.txt", "UTF-8");
    writer.println(szOutput) ; 
    writer.close();
  }

//Adds the XOR gate to the cipher
 public static void XorCipher(String[] binaryArray , String[] keyBinaryArray)
  {
    //Have a placement value of value0 = 0 to pad the binary to 8 bit binary
    //One by one store the data needed from array into a temporary variable
    //Split each digit from the data, and store it into a different variable
    //Two For Loops one runs on the length of the message (binaryArray.length) and another on the length of the binary data (8)
    //compare the digits at the given address and apply the XOR Cipher
    //0 and 0 gives 0
    //0 and 1 gives 1
    //1 and 0 gives 1
    //1 and 1 gives 0
    System.out.println("Applying the XOR gate...") ; 
    String iTemp; 
    String iTempBinary ;     
    int Length ; 
    String szFinished = "" ; 
    String[] XorApplied = new String [binaryArray.length] ; 
    //This loop will control the length of the message being encrypted
    for(int a = 0 ; a < binaryArray.length ; a ++)
    {
      iTemp = binaryArray[a] ;

      iTempBinary = keyBinaryArray[a] ; 
      Length = iTemp.length() ; 
      szFinished = "" ; 
      //Loop used for the indiviual characters in one 8 bit binary setup
      //Used to apply the XOR gate to both of the binaries
       for(int b = 0 ; b < 8 ; b++) 
       { 
          if(iTemp.charAt(b) == iTempBinary.charAt(b))
          {
            szFinished = (szFinished + "0") ;
          }
          else
          {
            szFinished = (szFinished + "1") ; 
          }
       }
//Each of these is then stored into an array
       XorApplied[a] = szFinished ;
     }
      //This was needed as it was throwing an IOException
      try {
            decodingXorCipher(XorApplied) ; 
        }
        catch (IOException e) {
            System.out.println("Error") ; 
        } 

  }  

  //Find binary values of each indiviual character in the message
  public static void findBinary(char[] keyArray , char[] messageArray) 
  {
    //Creates new arrays that are the same length of the message and key
    String [] binaryArray = new String[messageArray.length];
    String [] keyBinaryArray = new String[keyArray.length];
    String iTemp;  
    String keyTemp ;
    System.out.println("Converting Data to Binary...") ; 
    for(int i = 0 ; i < messageArray.length ; i++) 
     { 
        //Each element in the array is being converted to a binary value
        iTemp =  String.format("%8s", Integer.toBinaryString(messageArray[i])).replace(' ', '0');
        //The String value is being converted into an int data type

        //This is being stored into an array
        binaryArray[i] = iTemp ; 
        //This binary element is being stored into an array
       // System.out.println(binaryArray[i]) ; 
     }
    System.out.println();

    //Loop used to find ot the binary values of the key and store that into an array
    for(int k = 0 ; k < keyArray.length ;  k ++)
     {
     //Finds the binary values
       keyTemp =  String.format("%8s", Integer.toBinaryString(keyArray[k])).replace(' ', '0');          
     //Stores the int data type into an array
       keyBinaryArray[k] = keyTemp ; 
       //System.out.println(keyBinaryArray[k]) ; 
     }
    System.out.println("Data has been converted to Binary...") ;
    XorCipher(binaryArray , keyBinaryArray) ; 

  }

  //Taking all the variables in
  public static void main(String[] args) throws IOException
   {
     String key = "" ;
     String userMessage ;
     int iRandom , iSum ; 
     char letter ;
     String szBinary;  
     //Allows for the user input
     Scanner szKeyboard = new Scanner(System.in) ; 
     System.out.println("What is the text being encrypted? "); 
     userMessage = szKeyboard.nextLine() ; 
     //Removes all the spaces 
     userMessage = userMessage.strip() ;
     //A Random Key is Being Generated Everytime the Code is running
     for(int p = 0 ; p < userMessage.length() ; p++ )
     {
       //This is the random process, i have taken away 32 because it would give me output values that cannot be read from the ASCII table (1-31)
       iRandom = (int)(Math.random() * 223) ;
       //I added 32 making sure that i do not get a vlaue less than 32
       iSum = iRandom + 32 ; 
       //This number was changed to a binary value
       szBinary = Integer.toBinaryString(iSum) ;
       //The binary value was converted back into a char value
       letter = (binaryToChar(szBinary)); 
       //This is then connactnated to form the key
       key = key + letter ; 
     }
     //The key is stored into an array
     char[] keyArray = key.toCharArray() ;
     System.out.println("The Key is " + key) ; 
     //The message that is being incrypted it being stored into an cArray
     char [] messageArray = userMessage.toCharArray() ;
     System.out.println("Processing Data...") ;
     //This is used to save the message from the user into an external file 
     PrintWriter writer = new PrintWriter("Message.txt", "UTF-8");
     writer.println(userMessage);
     writer.close();
//This saves the key into an external file so it can be recorded to encrypt and decrypt the message
     PrintWriter kWriter = new PrintWriter("Key.txt", "UTF-8");
     kWriter.println(key);
     kWriter.close();


     szKeyboard.close() ;

     findBinary(messageArray , keyArray) ;

    }

  public static char binaryToChar(String binary)
  {
    int decimal = Integer.parseInt(binary, 2) ;
    return (char) decimal;
  }
}

Это код, который я сделал, о том, как работает Vernam Cipher, и я хотел получить go для него сам, я хотел знать, как я мог бы сделать его лучше, а также как чтобы исправить мою проблему с записью файлов, когда каждый раз, когда я буду запускать этот код, содержимое в файлах будет перезаписываться . Шифр Vernam работает, принимая сообщение (userMessage) и применяя ключ к сообщению в форме XOR Gate. Ключ в моем коде генерируется случайным образом, а затем оба эти значения сохраняются в массиве. Затем они передаются в другую функцию, а затем преобразуются в двоичные значения, после преобразования они сохраняются в другом массиве и затем передаются в другую функцию, которая применяет вентиль XOR и к ключу, и к сообщению (двоичные значения). После этого результат сохраняется в другом массиве и затем преобразуется из двоичного в текст ASCII. Пожалуйста, обратите внимание, мне 16 лет, я только начал программировать в течение 5-6 месяцев и пока не знаю много подробностей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...