Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在两个类之间传递数据返回null_Java_Android_Android Intent_Encryption_Rsa - Fatal编程技术网

Java 在两个类之间传递数据返回null

Java 在两个类之间传递数据返回null,java,android,android-intent,encryption,rsa,Java,Android,Android Intent,Encryption,Rsa,对不起,我是Android开发的新手,现在我在我的最后一个项目中遇到了这个简单的问题,我尝试了从stackoverflow中学到的所有东西,但都没有成功。 我的项目是一个简单的客户端/服务器加密消息应用程序。 我找到了示例代码并创建了类,这些类工作正常,但不能一起工作:( 类1(EncryptActivity)使用RSA对来自其自身输入的数据进行加密。 类2(MyActivity)与服务器建立TCP连接以发送纯文本 但当我想将纯文本从MyActivity发送到EncryptActivity并获取

对不起,我是Android开发的新手,现在我在我的最后一个项目中遇到了这个简单的问题,我尝试了从stackoverflow中学到的所有东西,但都没有成功。 我的项目是一个简单的客户端/服务器加密消息应用程序。 我找到了示例代码并创建了类,这些类工作正常,但不能一起工作:( 类1(EncryptActivity)使用RSA对来自其自身输入的数据进行加密。 类2(MyActivity)与服务器建立TCP连接以发送纯文本

但当我想将纯文本从MyActivity发送到EncryptActivity并获取加密文本时,我总是得到“null”

我试图传递数据的方式是使用注释“/”的代码

请帮助我:((

加密活动:

public class EncryptActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    try {
        generateKey();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.encryptinput);

    final Button enButton = (Button) findViewById(R.id.bEncrypt);
    final Button deButton = (Button) findViewById(R.id.bDecrypt);
    final EditText input = (EditText) findViewById(R.id.etPlainText);
    final EditText Raw = (EditText) findViewById(R.id.etEncryptedText);
    final EditText output = (EditText) findViewById(R.id.etDecryptedText);

    enButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            try {
                // Encrypted text
                Raw.setText(encrypt(input.getText().toString()));

                // Receive plain text from MyActivity
                //
                // Bundle gotContainer = getIntent().getExtras();
                // String gotPlainText = gotContainer.getString("key");
                // input.setText(gotPlainText);

                // Send encrypted to MyActivty
                //
                // Bundle container2 = new Bundle();
                // container2.putString(encrypt(input.getText().toString()),
                // "key2");
                // Intent myIntent2 = new Intent(EncryptActivity.this,
                // MyActivity.class);
                // myIntent2.putExtras(container2);
                // startActivity(myIntent2);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        };
    });

    deButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            try {
                output.setText(String.valueOf(decrypt(Raw.getText()
                        .toString())));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

}

private final static String RSA = "RSA";
public static PublicKey uk;
public static PrivateKey rk;

public static void generateKey() throws Exception {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA);
    gen.initialize(512, new SecureRandom());
    KeyPair keyPair = gen.generateKeyPair();
    uk = keyPair.getPublic();
    rk = keyPair.getPrivate();
}

private static byte[] encrypt(String text, PublicKey pubRSA)
        throws Exception {
    Cipher cipher = Cipher.getInstance(RSA);
    cipher.init(Cipher.ENCRYPT_MODE, pubRSA);
    return cipher.doFinal(text.getBytes());
}

public final static String encrypt(String text) {
    try {
        return byte2hex(encrypt(text, uk));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public final static String decrypt(String data) {
    try {
        return new String(decrypt(hex2byte(data.getBytes())));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

private static byte[] decrypt(byte[] src) throws Exception {
    Cipher cipher = Cipher.getInstance(RSA);
    cipher.init(Cipher.DECRYPT_MODE, rk);
    return cipher.doFinal(src);
}

public static String byte2hex(byte[] b) {
    String hs = "";
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
        stmp = Integer.toHexString(b[n] & 0xFF);
        if (stmp.length() == 1)
            hs += ("0" + stmp);
        else
            hs += stmp;
    }
    return hs.toUpperCase();
}

public static byte[] hex2byte(byte[] b) {
    if ((b.length % 2) != 0)
        throw new IllegalArgumentException("hello");

    byte[] b2 = new byte[b.length / 2];

    for (int n = 0; n < b.length; n += 2) {
        String item = new String(b, n, 2);
        b2[n / 2] = (byte) Integer.parseInt(item, 16);
    }
    return b2;
}
public class MyActivity extends Activity {

private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    arrayList = new ArrayList<String>();

    final EditText editText = (EditText) findViewById(R.id.editText);
    Button send = (Button) findViewById(R.id.send_button);

    // relate the listView from java to the one created in xml
    mList = (ListView) findViewById(R.id.list);
    mAdapter = new MyCustomAdapter(this, arrayList);
    mList.setAdapter(mAdapter);

    // connect to the server
    new connectTask().execute("");

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String message = editText.getText().toString();

            // String encMessage =
            // EncryptActivity.encrypt(editText.getText().toString());

            // Send plain text to EncryptActivity
            //
            // Bundle container = new Bundle();
            // container.putString(message, "key");
            // Intent myIntent = new Intent(MyActivity.this,
            // EncryptActivity.class);
            // myIntent.putExtras(container);
            // startActivity(myIntent);

            // Receive encrypted data from EncryptActivity
            //
            // Bundle gotContainer2 = getIntent().getExtras();
            // String gotEncrypted = gotContainer2.getString("key2");

            // add the text in the arrayList
            arrayList.add("Me: " + message);

            // sends the message to the server
            // Change message to gotEncrypted but doesn't work :(
            if (mTcpClient != null) {
                mTcpClient.sendMessage(message);
            }

            // refresh the list
            mAdapter.notifyDataSetChanged();
            editText.setText("");
        }
    });

}

public class connectTask extends AsyncTask<String, String, TCPClient> {

    @Override
    protected TCPClient doInBackground(String... message) {

        // we create a TCPClient object and
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            // here the messageReceived method is implemented
            public void messageReceived(String message) {
                // this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        mTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        // in the arrayList we add the messaged received from server
        arrayList.add(values[0]);
        // notify the adapter that the data set has changed. This means that
        // new message received
        // from server was added to the list
        mAdapter.notifyDataSetChanged();
    }
}
公共类EncryptActivity扩展活动{
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
试一试{
generateKey();
}捕获(异常e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.encryptinput);
最终按钮enButton=(按钮)findViewById(R.id.bEncrypt);
最终按钮去毛刺=(按钮)findViewById(R.id.bDecrypt);
最终EditText输入=(EditText)findViewById(R.id.etPlainText);
最终EditText原始=(EditText)findViewById(R.id.etEncryptedText);
最终EditText输出=(EditText)findViewById(R.id.etDecryptedText);
setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
试一试{
//加密文本
saw.setText(加密(input.getText().toString());
//从MyActivity接收纯文本
//
//Bundle-gotContainer=getIntent().getExtras();
//字符串gotplantext=gotContainer.getString(“key”);
//input.setText(gotplantext);
//发送加密到MyActivty
//
//Bundle container2=新Bundle();
//container2.putString(加密(input.getText().toString()),
//“键2”);
//Intent myIntent2=新的Intent(EncryptActivity.this,
//MyActivity.class);
//myIntent2.putExtras(容器2);
//起始触觉(myIntent2);
}捕获(例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
};
});
deButton.setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
试一试{
output.setText(String.valueOf(decrypt)(Raw.getText())
.toString());
}捕获(例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
});
}
私有最终静态字符串RSA=“RSA”;
公共静态公钥;
公共静态私钥;
public static void generateKey()引发异常{
KeyPairGenerator gen=KeyPairGenerator.getInstance(RSA);
gen.initialize(512,新的SecureRandom());
KeyPair KeyPair=gen.generateKeyPair();
uk=keyPair.getPublic();
rk=keyPair.getPrivate();
}
私有静态字节[]加密(字符串文本,公钥pubRSA)
抛出异常{
Cipher Cipher=Cipher.getInstance(RSA);
cipher.init(cipher.ENCRYPT_模式,publirsa);
返回cipher.doFinal(text.getBytes());
}
公共最终静态字符串加密(字符串文本){
试一试{
返回字节2hex(加密(文本,英国));
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
公共最终静态字符串解密(字符串数据){
试一试{
返回新字符串(解密(hex2byte(data.getBytes()));
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
私有静态字节[]解密(字节[]src)引发异常{
Cipher Cipher=Cipher.getInstance(RSA);
cipher.init(cipher.DECRYPT_模式,rk);
返回cipher.doFinal(src);
}
公共静态字符串字节2hex(字节[]b){
字符串hs=“”;
字符串stmp=“”;
对于(int n=0;n
}

MyActivity:

public class EncryptActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    try {
        generateKey();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.encryptinput);

    final Button enButton = (Button) findViewById(R.id.bEncrypt);
    final Button deButton = (Button) findViewById(R.id.bDecrypt);
    final EditText input = (EditText) findViewById(R.id.etPlainText);
    final EditText Raw = (EditText) findViewById(R.id.etEncryptedText);
    final EditText output = (EditText) findViewById(R.id.etDecryptedText);

    enButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            try {
                // Encrypted text
                Raw.setText(encrypt(input.getText().toString()));

                // Receive plain text from MyActivity
                //
                // Bundle gotContainer = getIntent().getExtras();
                // String gotPlainText = gotContainer.getString("key");
                // input.setText(gotPlainText);

                // Send encrypted to MyActivty
                //
                // Bundle container2 = new Bundle();
                // container2.putString(encrypt(input.getText().toString()),
                // "key2");
                // Intent myIntent2 = new Intent(EncryptActivity.this,
                // MyActivity.class);
                // myIntent2.putExtras(container2);
                // startActivity(myIntent2);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        };
    });

    deButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            try {
                output.setText(String.valueOf(decrypt(Raw.getText()
                        .toString())));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

}

private final static String RSA = "RSA";
public static PublicKey uk;
public static PrivateKey rk;

public static void generateKey() throws Exception {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA);
    gen.initialize(512, new SecureRandom());
    KeyPair keyPair = gen.generateKeyPair();
    uk = keyPair.getPublic();
    rk = keyPair.getPrivate();
}

private static byte[] encrypt(String text, PublicKey pubRSA)
        throws Exception {
    Cipher cipher = Cipher.getInstance(RSA);
    cipher.init(Cipher.ENCRYPT_MODE, pubRSA);
    return cipher.doFinal(text.getBytes());
}

public final static String encrypt(String text) {
    try {
        return byte2hex(encrypt(text, uk));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public final static String decrypt(String data) {
    try {
        return new String(decrypt(hex2byte(data.getBytes())));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

private static byte[] decrypt(byte[] src) throws Exception {
    Cipher cipher = Cipher.getInstance(RSA);
    cipher.init(Cipher.DECRYPT_MODE, rk);
    return cipher.doFinal(src);
}

public static String byte2hex(byte[] b) {
    String hs = "";
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
        stmp = Integer.toHexString(b[n] & 0xFF);
        if (stmp.length() == 1)
            hs += ("0" + stmp);
        else
            hs += stmp;
    }
    return hs.toUpperCase();
}

public static byte[] hex2byte(byte[] b) {
    if ((b.length % 2) != 0)
        throw new IllegalArgumentException("hello");

    byte[] b2 = new byte[b.length / 2];

    for (int n = 0; n < b.length; n += 2) {
        String item = new String(b, n, 2);
        b2[n / 2] = (byte) Integer.parseInt(item, 16);
    }
    return b2;
}
public class MyActivity extends Activity {

private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    arrayList = new ArrayList<String>();

    final EditText editText = (EditText) findViewById(R.id.editText);
    Button send = (Button) findViewById(R.id.send_button);

    // relate the listView from java to the one created in xml
    mList = (ListView) findViewById(R.id.list);
    mAdapter = new MyCustomAdapter(this, arrayList);
    mList.setAdapter(mAdapter);

    // connect to the server
    new connectTask().execute("");

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String message = editText.getText().toString();

            // String encMessage =
            // EncryptActivity.encrypt(editText.getText().toString());

            // Send plain text to EncryptActivity
            //
            // Bundle container = new Bundle();
            // container.putString(message, "key");
            // Intent myIntent = new Intent(MyActivity.this,
            // EncryptActivity.class);
            // myIntent.putExtras(container);
            // startActivity(myIntent);

            // Receive encrypted data from EncryptActivity
            //
            // Bundle gotContainer2 = getIntent().getExtras();
            // String gotEncrypted = gotContainer2.getString("key2");

            // add the text in the arrayList
            arrayList.add("Me: " + message);

            // sends the message to the server
            // Change message to gotEncrypted but doesn't work :(
            if (mTcpClient != null) {
                mTcpClient.sendMessage(message);
            }

            // refresh the list
            mAdapter.notifyDataSetChanged();
            editText.setText("");
        }
    });

}

public class connectTask extends AsyncTask<String, String, TCPClient> {

    @Override
    protected TCPClient doInBackground(String... message) {

        // we create a TCPClient object and
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            // here the messageReceived method is implemented
            public void messageReceived(String message) {
                // this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        mTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        // in the arrayList we add the messaged received from server
        arrayList.add(values[0]);
        // notify the adapter that the data set has changed. This means that
        // new message received
        // from server was added to the list
        mAdapter.notifyDataSetChanged();
    }
}
公共类MyActivity扩展活动{
私有ListView-mList;
私有ArrayList ArrayList;
私人MyCustomAdapter mAdapter;
私有TCP客户端mTcpClient;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
arrayList=新的arrayList();
final EditText EditText=(EditText)findViewById(R.id.EditText);
按钮发送=(按钮)findViewById(R.id.send_按钮);
//将java中的listView与xml中创建的listView关联起来
mList=(ListView)findViewById(R.id.list);
mAdapter=新的MyCustomAdapter(此为arrayList);
mList.setAdapter(mAdapter);
//连接到服务器
新建connectTask()。执行(“”);
send.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
String message=editText.getText().toString();
//字符串加密消息=
//EncryptActivity.encrypt(editText.getText().toString());
//将纯文本发送到加密活动
//
//Bundle container=新Bundle();
//putString(消息,“key”);
public void onCreate(Bundle savedInstanceState) {
    try {
        generateKey();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    super.onCreate(savedInstanceState);

    // Receive plain text from MyActivity
    String plainText = getIntent().getStringExtra("plainKey");
    String cipherText = encrypt(plainText);

    // Send encrypted to MyActivty
    Intent cryptIntent = new Intent(EncryptActivity.this, MyActivity.class);
    cryptIntent.putExtra("cipherKey", cipherText);
    startActivity(cryptIntent);
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    initialize();
}

private void initialize() {

    arrayList = new ArrayList<String>();
    editText = (EditText) findViewById(R.id.editText);
    Button send = (Button) findViewById(R.id.send_button);
    mList = (ListView) findViewById(R.id.list);
    mAdapter = new MyCustomAdapter(this, arrayList);
    mList.setAdapter(mAdapter);
    // connect to the server
    new connectTask().execute("");
    send.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {

    String plainText = editText.getText().toString();

    // Send plain text to EncryptActivity
    Intent plainIntent = new Intent(MyActivity.this, EncryptActivity.class);
    plainIntent.putExtra("plainKey", plainText);
    startActivity(plainIntent);

    // Receive encrypted data from EncryptActivity
    String message = getIntent().getStringExtra("cipherKey");

    // add the text in the arrayList
    arrayList.add("Me: " + plainText);

    // sends the message to the server
    if (mTcpClient != null) {
        mTcpClient.sendMessage(message);
    }

    // refresh the list
    mAdapter.notifyDataSetChanged();
    editText.setText("");
}