Caesar Cipher over TCP连接Android

时间:2011-03-23 18:11:55

标签: java android networking encryption tcp

我正在使用eclipse在android中构建这个应用程序。

我正在构建一个程序,它接受一个编码的凯撒密码字符串,然后找到移位的数量,然后发送回解码的文本。我遇到了很多问题所以我把程序分解为只解码两个字母的单词。我很少得到一个字符串返回给客户端,当我得到任何返回它通常是“空”。以下是我的课程:

此类对消息进行解码:

package com.mafia.ceasarCipher;
import java.util.ArrayList;
import android.util.Log;


public class ceasar{
    static Boolean cDB = new Boolean( false );
    int shift=0;
    fileInput dict= new fileInput();



public String cDecode(String input){
        char[] s = input.toCharArray();
        int length=0;

            for(int i=0;i < s.length;i++){ 
                if(s[i]!= ' '){
                    length++;
        }
    }

    String output;
    //char[] five=new char[5];
    //char[] four=new char[4];
    //char[] three=new char[3];
    char[] two=new char[2];
    boolean word = false;
        for(int i=0;i<s.length;i++){
            if(length==2){
                for(int j=0;j<2;j++){
                    two[j]=s[j];

                if(isWord(input,2))
                    Log.d("find", "proper" + "" + "checkWord");

                    word=true;
            }
        }
    if(word==true){
        output=shiftWord(input,shift);
        Log.d("find", "proper" + "" + "wordIsTrue");

            cDB =true;
            return output;          
    }}

        output="These are not words";
        cDB =true;

        return output;

        }


    public boolean isWord(String s,int length){
        ArrayList<String> d2=new ArrayList<String>();
        d2=dict.readD2();
        String st=s;
                if(length==2){
                    for(int i=0; i<26;i++){
                        for(int j=0;j<d2.size();j++){
                            if(st==d2.get(j))
                                Log.d("find", "proper" + "" + "isWord");

                                return true;
                }
                st=shiftWord(st,2);
                    shift+=1;


            }

        }

        return false;


    }
    public String shiftWord(String s,int length){
        Log.d("find", "proper" + "" + "shiftWord");
        char[] c=s.toCharArray();           
        for(int i=0;i<c.length;i++){
            for(int j=0;j<length;j++){
                if(c[i]=='a')
                    c[i]='z';
                else if(c[i]=='b')
                    c[i]='a';
                else if(c[i]=='c')
                    c[i]='b';
                else if(c[i]=='d')
                    c[i]='c';
                else if(c[i]=='e')
                    c[i]='d';
                else if(c[i]=='f')
                    c[i]='e';
                else if(c[i]=='g')
                    c[i]='f';
                else if(c[i]=='h')
                    c[i]='g';
                else if(c[i]=='i')
                    c[i]='h';
                else if(c[i]=='j')
                    c[i]='i';
                else if(c[i]=='k')
                    c[i]='j';
                else if(c[i]=='l')
                    c[i]='k';
                else if(c[i]=='m')
                    c[i]='l';
                else if(c[i]=='n')
                    c[i]='m';
                else if(c[i]=='o')
                    c[i]='n';
                else if(c[i]=='p')
                    c[i]='o';
                else if(c[i]=='q')
                    c[i]='p';
                else if(c[i]=='r')
                    c[i]='q';
                else if(c[i]=='s')
                    c[i]='r';
                else if(c[i]=='t')
                    c[i]='s';
                else if(c[i]=='u')
                    c[i]='t';
                else if(c[i]=='v')
                    c[i]='u';
                else if(c[i]=='w')
                    c[i]='v';
                else if(c[i]=='x')
                    c[i]='w';
                else if(c[i]=='y')
                    c[i]='x';
                else if(c[i]=='z')
                    c[i]='y';
            }
        }
        return c.toString();
    }


    }

这是服务器

 package com.mafia.ceasarCipher;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;

public class Server implements Runnable {
    //  Public boolean cDecodeStatus= new boolean();
        public static final String SERVERIP = "127.0.0.1"; // 'Within' the emulator!
        public static final int SERVERPORT = 4444;
        public ceasar c = new ceasar(); 
        public int byteCounter;


              public void run ()
              {
                  try{
                             String clientSentence;
                             String modifiedSentence;
                             ServerSocket welcomeSocket = new ServerSocket(SERVERPORT);

                             while(true)
                             {
                                Socket connectionSocket = welcomeSocket.accept();
                                BufferedReader inFromClient =
                                new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                                DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                                clientSentence = inFromClient.readLine();
                                Log.e( "Jake" ,"RECIEVED from client" + clientSentence);
                                //modifiedSentence = clientSentence.toUpperCase() + '\n';

                                modifiedSentence = c.cDecode(clientSentence );

                                Log.d("face", modifiedSentence);
                                System.out.println("before while"+' '+ ceasar.cDB);

                                while(ceasar.cDB!=true){
                                    //System.out.println("before if"+' '+ ceasar.cDB);
                                    //if(ceasar.cDB==true)
                                        //Log.d("send", "sending Loop");
                                    //System.out.println(ceasar.cDB);
                                outToClient.writeBytes(modifiedSentence);

                                }

                             }

                          }
               catch (Exception e) {
                   Log.e("UDP", "S: Error", e);
               }
              }
}

这是类在

中读取字典
package com.mafia.ceasarCipher;



import java.io.*;          
import android.os.Environment;
import android.util.Log;
import java.util.ArrayList;
public class fileInput

{
  public ArrayList<String> readD2(){

      File sdcard = Environment.getExternalStorageDirectory();
      //Get the text file
      File file = new File(sdcard,"d2.txt");
      //Read text from file

      try {
          BufferedReader br = new BufferedReader(new FileReader(file));


          ArrayList<String> x  = new ArrayList <String>() ;
              String str;
              str = br.readLine();
              while(str != null) {

                str = br.readLine();
                x.add(str) ;

          }
               return x;
      }
      catch (IOException e) {
          return null;
      }


    }

这是客户

package com.mafia.ceasarCipher;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import android.util.Log;


public class Client implements Runnable {
     static String messageInput = new String(); 
    // static String modifiedSentence= new String();

    /*public static String getOutput(){
        return modifiedSentence;
    }*/


     public static void setCode(String x)
     {
           messageInput= x;
     }



        @Override
        public void run() {
            try{
                Log.d("Step", "1");
                Socket clientSocket = new Socket("localhost", 4444);
                Log.d("Step", "2");

                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                Log.d("Step", "3");


                Log.d("Step", "4");


              BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                Log.d("Step", "5");

              outToServer.writeBytes(messageInput + '\n');
                Log.d("Step", "6");
                String modifiedSentence;

             modifiedSentence = inFromServer.readLine();
                Log.d("Step", "7");


             Log.e( "Jake" ,"RECIEVED BACK FROM SERVER: " + modifiedSentence);


              clientSocket.close();
             }
                catch (Exception e) {
              Log.e("UDP", "C: Error", e);}
                }




        }

此类处理onCreate和onClick方法

package com.mafia.ceasarCipher;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class udpConnection extends Activity {



         String input = "";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);

            final Button button1 = (Button)findViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {
                    /* Kickoff the Server, it will
                     * be 'listening' for one client packet */
                    new Thread(new Server()).start();
                    final EditText et = (EditText)findViewById(R.id.editText1);
                    input = et.getText().toString();

                    /*Log.d("UDP","input is"+ input);
                    final TextView TV = (TextView)findViewById(R.id.textView2);
                    String out= Client.getOutput();
                    TV.setText(out);*/

                    /* GIve the Server some time for startup */
                    try {
                                    Thread.sleep(500);
                            } catch (InterruptedException e) { }

                    // Kickoff the Client
                    new Thread(new Client()).start();
                    Client.setCode(input );

                }
            });   


        }
        public String getInput()
        {

            return input;
        }

    }

GUI

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout android:id="@+id/mainLayout"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <TextView android:layout_height="wrap_content"
            android:layout_alignParentTop="true" android:id="@+id/textView1"
            android:layout_width="fill_parent" android:gravity="center"
            android:textSize="24px" android:text="Networking" />
        <EditText android:layout_height="wrap_content" android:id="@+id/editText1"
            android:layout_width="wrap_content" android:layout_below="@+id/textView1"
            android:layout_alignLeft="@+id/textView1" android:layout_alignRight="@+id/textView1"
            android:hint="Enter coded text here!" android:isScrollContainer="true" android:editable="true"/>
        <Button android:layout_height="wrap_content"
            android:layout_width="wrap_content" android:id="@+id/button1"
            android:layout_below="@+id/editText1" android:layout_alignLeft="@+id/editText1"
            android:layout_alignRight="@+id/editText1" android:text="Send message" />
        <TextView android:layout_height="wrap_content"
            android:layout_width="wrap_content" android:layout_below="@+id/button1"
            android:id="@+id/textView2" android:layout_alignLeft="@+id/button1"
            android:layout_alignRight="@+id/button1" android:hint="Message will show here!" 
            android:editable="true" android:isScrollContainer="true"/>
        <Button android:layout_below="@+id/textView2" android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_alignRight="@+id/textView2" android:text="Display Text"></Button>
    </RelativeLayout>
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

首先,我不认为它返回null。我不认为你可以将一个字符数组转换成这样的字符串。这是将字符数组转换为字符串

的正确方法
String s = new String(array); // array is just the name of an array of characters

在你的shiftWord方法中尝试这个。请注意我所做的唯一更改是: 添加一个名为d的String,然后在底部设置新的String d作为你的字符数组,然后返回String d。

其次,我不明白为什么你在shiftWord方法中有一个嵌套循环。我认为,如果你删除第二个并保留第一个相同,那么它应该可以工作。

免责声明:我没有测试任何这个:)祝你好运!

public String shiftWord(String s,int length){
        String d;
        Log.d("find", "proper" + "" + "shiftWord");
        char[] c=s.toCharArray();           
        for(int i=0;i<c.length;i++){
                if(c[i]=='a')
                    c[i]='z';
                else if(c[i]=='b')
                    c[i]='a';
                else if(c[i]=='c')
                    c[i]='b';
                else if(c[i]=='d')
                    c[i]='c';
                else if(c[i]=='e')
                    c[i]='d';
                else if(c[i]=='f')
                    c[i]='e';
                else if(c[i]=='g')
                    c[i]='f';
                else if(c[i]=='h')
                    c[i]='g';
                else if(c[i]=='i')
                    c[i]='h';
                else if(c[i]=='j')
                    c[i]='i';
                else if(c[i]=='k')
                    c[i]='j';
                else if(c[i]=='l')
                    c[i]='k';
                else if(c[i]=='m')
                    c[i]='l';
                else if(c[i]=='n')
                    c[i]='m';
                else if(c[i]=='o')
                    c[i]='n';
                else if(c[i]=='p')
                    c[i]='o';
                else if(c[i]=='q')
                    c[i]='p';
                else if(c[i]=='r')
                    c[i]='q';
                else if(c[i]=='s')
                    c[i]='r';
                else if(c[i]=='t')
                    c[i]='s';
                else if(c[i]=='u')
                    c[i]='t';
                else if(c[i]=='v')
                    c[i]='u';
                else if(c[i]=='w')
                    c[i]='v';
                else if(c[i]=='x')
                    c[i]='w';
                else if(c[i]=='y')
                    c[i]='x';
                else if(c[i]=='z')
                    c[i]='y';
            }
        }
        d = new String(c);
        return d;       
    }