2011-10-30 18 views
5

realmente necesito saber cómo se codificar esto o algo similar en Java: http://www.cs.carleton.edu/faculty/adalal/teaching/f05/107/applets/ascii.htmlProgramación de un programa de cifrado (Texto sin formato-> Cifrado César-> ASCII)?

Aquí está mi intento He estado en ella todo el día (literalmente) y han tenido que buscar en la forma de hacerlo en Internet porque sino porque mi conocimiento de Java no es tan bueno que no puedo entender ninguno (al principio de hoy no sabía nada que ver con las matrices) de todo lo que necesito es un poco de ayuda o un empujón en la derecha dirección.

[edit] Lo siento, me olvidé de señalar la pregunta. Lo que estoy teniendo problemas no es convertir y cifrar el texto plano, sino intentar convertir un mensaje codificado (cifrado con mi programa, por supuesto) en texto plano (es decir, no puedo revertirlo con la variable en mi programa, de hecho, tengo que ser capaz de leer y decodificar)

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); 
    } 
} 
+4

Java no es ** JavaScript **. –

+0

Editar: fecha de vencimiento eliminada, ya que no está relacionado con el problema de codificación en cuestión. –

+0

Deslizamiento del mouse lo siento chicos no fue ofender. – ChaseVsGodzilla

Respuesta

0

parece que el cifrado simplemente desplaza cada carácter del mensaje por un valor dado.

int letterCiphered= (letter-key2); 

descifrar un mensaje de este tipo se debe cambiar cada carácter del cifrado por el mismo valor, pero en la otra dirección.

int letter= (letterCiphered+key2); 

La función de descifrado que tiene en el código hace algo completamente diferente.

actualización siguiendo los comentarios:

si he entendido bien que desea convertir una cadena de valores ASCII de texto que representan.

Para analizar la cadena de entrada, si se trata de un formato simple, puede simplemente usar String.split() leer sobre él.
Para convertir una representación textual de un número en un número real, puede usar Integer.parseInt().
Por último, a su vez un valor entero ASCII a un personaje sólo tiene que echar char c = (char)97;

analiza la entrada para identificar cada valor ascii, convertir cada valor a un entero y echarlo a un personaje, a continuación, sólo concatenar los caracteres a una cadena.

+0

Sí, es un cifrado César pero luego las letras se convierten a sus valores ASCII correspondientes y se almacenan en una matriz. Esta matriz se muestra en mi JTextField y lo siento, estaba ocupado metiéndome con algunas ideas cuando publiqué esto, sé cómo descifrarlo. Mi problema no es el descifrado real sino más bien cómo obtengo solo pares de valores ASCII del texto ingresado y los convierto en texto (caracteres) si sigues la URL verás lo que quiero decir, no cifra el texto, pero convierte el char a ASCII y viceversa. – ChaseVsGodzilla

+0

bytes se pueden convertir a caracteres simplemente fundiéndolos en él: (char). O una cadena se puede formar a partir de una matriz de bytes a través de 'new String (myByteArray)'. Quizás desee utilizar una matriz de bytes y no una matriz int. –

+0

Estaba leyendo algo antes sobre String Methods para la coincidencia de patrones 2 parecía prometedor 'match()' y 'replace()' podrían ser una posibilidad, ya que dije que en realidad no lo entiendo, así que no pude implementarlo. – ChaseVsGodzilla

1

Resuelto

Esta es la forma en que serán encriptados mi texto:

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); 
} 

Así es como me descifrado mi texto

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"); 
} 

Gracias por todo el ayuda chicos resultó mucho más simple de lo que pensaba.

-3
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 ""; 
    } 
} 
}