Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.bos3;
- import androidx.appcompat.app.AppCompatActivity;
- import android.os.Bundle;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.view.View;
- import android.widget.Button;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.InputStream;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.nio.*;
- import java.nio.charset.Charset;
- import java.security.*;
- import java.security.spec.*;
- import javax.crypto.spec.*;
- import javax.crypto.*;
- import android.util.Base64;
- public class MainActivity extends AppCompatActivity {
- Thread Thread1 = null;
- EditText serverIP, serverPort;
- EditText userMessage;
- TextView chatMessages;
- Button btnSend;
- Thread ThreadConnect = null;
- String SERVER_IP;
- int SERVER_PORT;
- InputStream in_stream;
- OutputStream soc_out_stream;
- Cipher cipher;
- Cipher cipher_d;
- Cipher cipher_rsa;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- serverIP = findViewById(R.id.editIp);
- serverPort = findViewById(R.id.editPort);
- // Значения по умолчанию
- serverIP.setText("10.0.2.2"); // Вместо 127.0.0.1 используем этот адрес
- serverPort.setText("9001");
- chatMessages = findViewById(R.id.chatId);
- userMessage = findViewById(R.id.userMsg);
- btnSend = findViewById(R.id.btnSend);
- Button btnConnect = findViewById(R.id.btnConnect);
- btnConnect.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- chatMessages.setText("");
- SERVER_IP = serverIP.getText().toString().trim();
- SERVER_PORT = Integer.parseInt(serverPort.getText().toString().trim());
- Thread ThreadConnect = new Thread(new ThreadConnect());
- ThreadConnect.start();
- }
- });
- Button btnSend = findViewById(R.id.btnSend);
- btnSend.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String userMsg = userMessage.getText().toString().trim();
- if (!userMsg.isEmpty()) {
- new Thread(new ThreadSendMsg(userMsg)).start();
- }
- }
- });
- }
- private PrintWriter output;
- private BufferedReader input;
- class ThreadConnect implements Runnable {
- @Override
- public void run() {
- Socket socket;
- try {
- socket = new Socket(SERVER_IP, SERVER_PORT);
- soc_out_stream = socket.getOutputStream();
- output = new PrintWriter(soc_out_stream);
- input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- in_stream = socket.getInputStream();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- chatMessages.setText("Connected to server\n");
- }
- });
- new Thread(new ChatThread()).start();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- class ChatThread implements Runnable {
- @Override
- public void run() {
- //Handshake
- String keyBytes = "";
- try {
- String line = input.readLine();
- while (!line.equals("-----END PUBLIC KEY-----")) {
- keyBytes += line + "\n";
- line = input.readLine();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- String pubKeyPEM = keyBytes.replace("-----BEGIN PUBLIC KEY-----\n", "");
- pubKeyPEM = pubKeyPEM.replace("-----END PUBLIC KEY-----", "");
- byte[] encoded = Base64.decode(pubKeyPEM, android.util.Base64.DEFAULT);
- X509EncodedKeySpec spec =
- new X509EncodedKeySpec(encoded);
- final PublicKey pub_key;
- try {
- cipher_rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
- } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
- e.printStackTrace();
- }
- try {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- pub_key = kf.generatePublic(spec);
- cipher_rsa.init(Cipher.ENCRYPT_MODE, pub_key);
- } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException e) {
- System.err.println("");
- }
- byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- IvParameterSpec ivspec = new IvParameterSpec(iv);
- try {
- SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
- SecureRandom r = new SecureRandom();
- byte[] aesKey = new byte[16];
- r.nextBytes(aesKey);
- try {
- cipher_rsa.update(aesKey);
- try {
- byte[] cipherText = cipher_rsa.doFinal();
- soc_out_stream.write(cipherText);
- soc_out_stream.flush();
- } catch (BadPaddingException | IllegalBlockSizeException e) {
- e.printStackTrace();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- SecretKey tmp = new SecretKeySpec(aesKey, "AES");
- cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- cipher_d = Cipher.getInstance("AES/ECB/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, tmp);
- cipher_d.init(Cipher.DECRYPT_MODE, tmp);
- AlgorithmParameters params = cipher.getParameters();
- } catch (NoSuchAlgorithmException | NoSuchPaddingException
- | InvalidKeyException e) {
- e.printStackTrace();
- }
- while (true) {
- try {
- final byte[] message = new byte[4096];
- final int recv = in_stream.read(message);
- if (message != null) {
- // cipher_d.update(Base64.decode(message, android.util.Base64.DEFAULT));
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- try {
- byte[] cyph = new byte[recv];
- System.arraycopy(message, 0, cyph, 0, recv);
- byte[] plain = cipher_d.doFinal(cyph);
- String msg = new String(plain, Charset.forName("UTF-8"));
- chatMessages.append("Server: " + msg + "\n");
- } catch (BadPaddingException | IllegalBlockSizeException e) {
- e.printStackTrace();
- }
- }
- });
- } else {
- ThreadConnect = new Thread(new ThreadConnect());
- ThreadConnect.start();
- return;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- class ThreadSendMsg implements Runnable {
- private String message;
- ThreadSendMsg(String message) {
- this.message = message;
- }
- @Override
- public void run() {
- byte[] b = message.getBytes();
- cipher.update(b);
- try {
- byte[] cipher_text = cipher.doFinal();
- soc_out_stream.write(cipher_text);
- soc_out_stream.flush();
- } catch (BadPaddingException | IllegalBlockSizeException | IOException e) {
- e.printStackTrace();
- }
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- chatMessages.append("Сlient: " + message + "\n");
- userMessage.setText("");
- }
- });
- }
- }
- }
Add Comment
Please, Sign In to add comment