如何使用加密程序创建解密程序?

时间:2014-04-06 01:58:45

标签: java encryption methods

如何将我的加密代码转换为用于解密?我不希望它们在同一个程序中用于两个不同的文件。我需要帮助弄清楚如何将此代码的一部分用于我的解密代码。基本上我需要使用这个代码并找到一种方法来使用它来创建另一个程序来解密由下面的代码创建的代码。

我用于加密的代码是:

import java.util.*;

public class Cipher //This class will encrpyt the program
{

  public static char cipher (int j){ //this mehtod generates the random letter
    char[] cipher1 = {'a','b','c','d','e','f','g'}; //characters for char array
    j = (int) (Math.random() * cipher1.length);//choose a random element from the array
    return cipher1[j]; //this will return the letter
  } //end of cipher method

  public static void main (String[] args){ //main method

    System.out.print("Please type a sentence to be encrypted\n");//asks user for their word to be encrypted
    Scanner inputScanner = new Scanner(System.in); //imports scanner reader
    String userinput = inputScanner.next(); //assigns the word entered by user to varible userinput
    userinput = userinput.toUpperCase(); //userinput in transferred to upper case letters
    int yu = userinput.length(); //yu finds the length of charceters in userinput
    char[] charArray = userinput.toCharArray(); //sends userinput to charArray

    int w=1; //used for try catch block
    System.out.println("please enter pattern"); //prompt for pattern
    String pattern = inputScanner.next(); //pattern will decide how many characters will be input in the encrypted code
    int pattern2 = Integer.parseInt(pattern); //changes the string value to integer value

    do{ 
      try{ //try block to catch if user enters letters or decimal numbers
        w=2;
        if(pattern2<0){
          System.out.println("please enter a number above 0"); //prompt if user enters somthing below zero
          w=1;
        }
      }catch (NumberFormatException f){
        System.out.println("PLEASE ENTER A NUMBER!"); //prompt if user enters something user than a number
      }

    }while (w==1); //end of do and try catch block

    System.out.print("your encrypted code is: "); //prompt to give user encrypted code

    for(int i = 0; i < yu; i++){
      System.out.print(charArray[i]);
      for(int q = 0; q < pattern2; q++){
        System.out.print( cipher(1));
      } //end of for loop
    } //end of for loop

  } //end of main method
} //cipher class

1 个答案:

答案 0 :(得分:1)

不,代码仅用于加密。从代码似乎就像是One Time Pad

对于解密,您需要知道反向逻辑,例如了解接收器如何知道已经进行了哪些更改以及如何撤消它们。首先阅读实践背后的理论:)