java 编程密码程序(纯文本->凯撒密码-> ASCII)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7946166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:08:22  来源:igfitidea点击:

Programming a Cipher Program (Plain Text->Caesar Cipher->ASCII)?

javaasciiencryption

提问by ChaseVsGodzilla

I really need to know how you would code this or something similar in Java: http://www.cs.carleton.edu/faculty/adalal/teaching/f05/107/applets/ascii.html

我真的需要知道你将如何在 Java 中编码这个或类似的东西:http: //www.cs.carleton.edu/faculty/adalal/teaching/f05/107/applets/ascii.html

Here is my attempt I've been at it the whole day (literally) and have had to search on how to do it on the internet because but because my Java knowledge not so great I can't understand any (At the start of today I didn't know anything to do with arrays) of it all I need is a little help or a push in the right direction.

这是我的尝试,我一整天(字面意思)都在尝试,并且不得不在互联网上搜索如何做到这一点,因为但是因为我的 Java 知识不是那么好,我无法理解任何(今天开始时我不知道与数组有什么关系)我需要的只是一点帮助或朝着正确的方向推动。

[edit] Sorry forgot to point out the question. What I'm having trouble with is not converting and ciphering the PlainText but trying to convert a encoded message (ciphered with my program of course) to PlainText (i.e I can't just reverse it with the variable in my program I actually have to be able to read it and decode it)

[编辑] 抱歉忘了指出问题。我遇到的问题不是转换和加密纯文本,而是尝试将编码消息(当然是用我的程序加密)转换为纯文本(即我不能只是用我的程序中的变量来反转它我实际上必须能够阅读它并解码它)

private void encryptBUTActionPerformed(java.awt.event.ActionEvent evt)    
{                                           
    int encryptLength=encryptTXT.getText().length();
    int[] anArray=new int[encryptLength];
    String key=encryptKey.getText();
    if(key.isEmpty())
    {
        decryptTXT.setText(""+"INVALID KEY");
    }
    else
    {
        int key2=Integer.parseInt(key);
        for(int i=0;i<encryptLength;i++)
        {
            int letter = encryptTXT.getText().toLowerCase().charAt(i);
            System.out.println(letter);
            System.out.println((char)letter);
            int letterCiphered= (letter-key2);
            anArray[i]=letterCiphered;
        }
        String output=(Arrays.toString(anArray));
        decryptTXT.setText(output);
    }
}                                          

private void clearBUTActionPerformed(java.awt.event.ActionEvent evt)               
{                                         
mainPassword.setText("");
encryptTXT.setText("");
decryptTXT.setText("");
encryptKey.setText("");
decryptKey.setText("");
}                                        

private void decryptBUTActionPerformed(java.awt.event.ActionEvent evt)     
{                                           
    int textLength=decryptTXT.getText().length();
    ArrayList list=new ArrayList();
    String text=decryptTXT.getText();
    int count=1;
    String key=decryptKey.getText();
    if(key.isEmpty())
    {
        encryptTXT.setText(""+"INVALID KEY");
    }
    else
    {
        int key2=Integer.parseInt(key);
        for(int i=0;i<textLength;i++)
        {
            if(text.charAt(i)=='['||text.charAt(i)==','||text.charAt(i)==']')
            {
                count=count+1;
            }
            else if(count%2==0)
            {
                char number=text.charAt(i);
                char number2=text.charAt(i+1);
                int num=(int)number;
                int num2=(int)number2;
                int num3=num;
                int num4=num3+num2-15;
                int num5=num4+key2;
                char letter2=(char)num5;
                list.add(letter2);
                count=count+1;
            }
            else
            {

            }
        }
        Object[] obj=(list.toArray());
        String out=Arrays.toString(obj);
        encryptTXT.setText(out);
    }
}

回答by ChaseVsGodzilla

Solved

解决了

This is how I encrypted my text:

这是我加密文本的方式:

int encryptLength=encryptTXT.getText().length();
String key=encryptKey.getText();
String text="";
if(key.isEmpty())
{
    decryptTXT.setText(""+"INVALID KEY");
}
else
{
    int key2=Integer.parseInt(key);
    for(int i=0;i<encryptLength;i++)
    {
        int letter = encryptTXT.getText().toLowerCase().charAt(i);
        int letterCiphered = (letter-key2);
        text=text+letterCiphered+" ";
    }
    decryptTXT.setText(""+text);
}

This is how I decrypted my text

这就是我解密文本的方式

try
{
String text=decryptTXT.getText();
String key=decryptKey.getText();
String[] decrypt=text.split(" ");
String sentance="";
if(key.isEmpty())
{
    encryptTXT.setText(""+"INVALID KEY");
}
else
{
    int key2=Integer.parseInt(key);
    for(int i=0;i<decrypt.length;i++)
    {
        int number=Integer.parseInt(decrypt[i]);
        char letter=(char)(number+key2);
        sentance=sentance+letter;
    }
    encryptTXT.setText(""+sentance);
}
}
catch(NumberFormatException e)
{
    encryptTXT.setText(""+"Please enter a valid encoded message");
}

Thanks for all the help guys turned out a lot simpler than I thought.

感谢所有的帮助,结果比我想象的要简单得多。

回答by yurib

It seems that your encryption just shifts every character of the message by a given value.

似乎您的加密只是将消息的每个字符移动了一个给定的值。

 int letterCiphered= (letter-key2);

To decipher such a message you should shift each character of the cipher by the same value but in the other direction.

要破译这样的消息,您应该将密码的每个字符移动相同的值,但在另一个方向上。

 int letter= (letterCiphered+key2);

The decryption function you have in the code does something else entirely.

您在代码中的解密函数完全做其他事情。

update following the comments:

根据评论更新:

If i understand correctly you want to convert a string of ascii values to the text they represent.

如果我理解正确,您想将一串 ascii 值转换为它们所代表的文本。

To parse the input string, if it's a simple format, you could just use String.split()read about it.
To convert a textual representation of a number to an actual number you could use Integer.parseInt().
Finally, to turn an integer ascii value to a character you only need to cast char c = (char)97;

要解析输入字符串,如果它是一个简单的格式,您可以使用String.split()read about it。
要将数字的文本表示转换为实际数字,您可以使用Integer.parseInt().
最后,要将整数 ascii 值转换为字符,您只需要强制转换char c = (char)97;

Parse the input to identify each ascii value, convert each value to an integer and cast it to a character, then just concatenate the characters to a string.

解析输入以识别每个 ascii 值,将每个值转换为整数并将其转换为字符,然后将字符连接为字符串。

回答by user8363140

package cipher;

import java.io.*;
import java.util.Scanner;

public class Cipher {

    public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
    public static final String ADDRESS = "C:\Users\abhati\Documents\NetBeansProjects\Cipher\encode.txt";
    public static final String LOCATE = "C:\Users\abhati\Documents\NetBeansProjects\Cipher\decode.enc";


    public static int MenuOption() throws Exception
    {
       int option;
 do{

        System.out.println("    +++++++++++++++++++\n    +   1. Encrypt    +");
        System.out.println("    +++++++++++++++++++\n    +   2. Decrypt    +");
        System.out.println("    +++++++++++++++++++\n    +   3.  Quit      + \n    +++++++++++++++++++");
        System.out.println("\nWhat would you like to do?");
        Scanner input = new Scanner(System.in); 
        option = input.nextInt();

        switch(option)
        {
            case 1:     encrypt();
                        break;

            case 2:     decrypt();
                        break;       

            case 3:     System.exit(0);
                        break;
            default: System.out.println("WRONG INPUT ??? PLEASE SELECT THE OPTION \n");
        }

    } while(option != 3);
              return option;   
 }

    public static void main(String[] args) throws Exception
    {
      System.out.println("Hello to Change Your text into cipher text!!!!\n");
      System.out.println("Put your text file in root folder.\n");
      MenuOption();
      System.out.println();
    }


    public static void encrypt() throws Exception {

     String ex;   
     FileReader in=null;
     FileWriter out = null;
      try {

          File file = new File(ADDRESS);
          in = new FileReader(file);
          file.getName();

          ex=getFileExtensionE(file);

          if(ex.equals("txt"))
         {
         out = new FileWriter(LOCATE);

         Scanner input2 = new Scanner(System.in); 
         System.out.println("What is the value for the key?");
         int key = input2.nextInt();


        Scanner input3 = new Scanner(in);
        while (input3.hasNext()) {
        String line = input3.nextLine();
        line = line.toLowerCase();
        String crypt = "";

        for (int i = 0; i < line.length(); i++) {
        int position = ALPHABET.indexOf(line.charAt(i));
        int keyValue = (key + position) % 26;
        char replace = ALPHABET.charAt(keyValue);
        crypt += replace;
        }
        out.write(""+crypt);
        System.out.println(""+crypt);
        }
        input3.close();
        System.out.println("\nDATA ENCRYPTED\n");
         }
        else 
         {
         System.out.println("DOESN'T ENCRYPTED!");   
                 }
    } catch(Exception e)
    {
        System.out.println("\n NO FILE FOUND WITH THIS NAME!!!");   
    }
        finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
}

    public static void decrypt() throws Exception {

      String ex;
      FileReader in = null;
      FileWriter out = null;
      try {

         File file = new File(LOCATE);
         in = new FileReader(file);
         file.getName(); 

         ex=getFileExtensionD(file);

          if(ex.equals("enc"))
         {
         out = new FileWriter("encrpted_DATA.txt");

         Scanner input4 = new Scanner(System.in); 
         System.out.println("What is the value for the key?");
         int key = input4.nextInt();                    

        Scanner input5 = new Scanner(in);
        while (input5.hasNext()) {
        String line = input5.nextLine();
        line = line.toLowerCase();
        String decrypt = "";

        for (int i = 0; i < line.length(); i++) {
        int position = ALPHABET.indexOf(line.charAt(i));
        int keyValue = (position - key) % 26;
         if (keyValue < 0)
            {
                keyValue = ALPHABET.length() + keyValue;
            }
        char replace = ALPHABET.charAt(keyValue);
        decrypt += replace;
        }
        out.write(""+decrypt);
        System.out.println(""+decrypt);
        }
        input5.close();
        System.out.println("\nDATA DECRYPTED\n");

        }
        else 
         {
          System.out.println("DOESN'T DECRYPTED!");   
         }
      }  catch(Exception e)
    {
        System.out.println("\n NO FILE FOUND WITH THIS NAME!!!");   
    }
         finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
    }
}

    public static String getFileExtensionE(File file) {
    String name = file.getName();
    try {
        return name.substring(name.lastIndexOf(".") + 1);
    } catch (Exception e) {
        return "";
    }
}

    public static String getFileExtensionD(File file) {
    String name = file.getName();
    try {
        return name.substring(name.lastIndexOf(".") + 1);
    } catch (Exception e) {
        return "";
    }
}  
}