Java套接字将加密的字符串发送到Python套接字

时间:2018-07-28 16:34:00

标签: java python sockets

我无法尝试使用SOCKETS将我的JAVA加密字符串发送到Python端。如果有人指出我的错误,那就太好了。对不起,麻烦了!

我能够将某些东西从Java发送到Python(可以接收)。

但是当我尝试将某些内容从Python发送到Java时,我不确定Java Side是否能够检索到它

这是我的密码

JAVA(客户端):

问题位于: sendEncryption()函数

    public class Discovery {

    byte[] buffer;

    public Socket socketStartConnect() throws UnknownHostException, IOException {
        String ip = "192.168.0.100";
        int port = 1234;
        Socket clientSocket = new Socket(ip, port);
        if (clientSocket.isConnected()) {
            System.out.println("It is connected to the server which is " +clientSocket.getInetAddress());

        } else if (clientSocket.isClosed()) {
            System.out.println("Connection Failed");
        }
        return clientSocket;
    }

    public byte[] encryption(String str) throws UnsupportedEncodingException, NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {

        Cipher aesCipher = Cipher.getInstance("AES");

        aesCipher.init(Cipher.ENCRYPT_MODE, secretkey());
        byte[] textEncrypted = aesCipher.doFinal(str.getBytes());

        System.out.println("Text encrypted : " + textEncrypted.toString());

        aesCipher.init(Cipher.DECRYPT_MODE, secretkey());
        byte[] textDecrypted = aesCipher.doFinal(textEncrypted);

        System.out.println("Text Decryted : " + new String(textDecrypted));

        return textEncrypted;
    }

    public byte[] decryption(String encryption) throws IllegalBlockSizeException, BadPaddingException,
            InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {

        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secretkey());
        byte[] textDecrypted = aesCipher.doFinal(encryption.getBytes());

        System.out.println("Text Decryted : " + new String(textDecrypted));
        return textDecrypted;

    }

    public SecretKey secretkey() {
        byte[] kBytes = new byte[16];
        SecretKey secretKey = null;

        try {
            String passString = "1234567890123456";
            byte[] passByte = passString.getBytes("UTF-8");
            System.arraycopy(passByte, 0, kBytes, 0, Math.min(kBytes.length, passByte.length));
            secretKey = new SecretKeySpec(kBytes, "AES");
        } catch (UnsupportedEncodingException e) {

        }
        return secretKey;
    }



    public void sendEncryption(byte[] encryption) throws Exception {

        // Get the socket's output stream
        Socket socket = socketStartConnect();
        OutputStream socketOutput = socket.getOutputStream();

        // total byte
        byte[] totalByteCombine = new byte[encryption.length];
        System.arraycopy(encryption, 0, totalByteCombine, 0, encryption.length);

        socketOutput.write(totalByteCombine, 0, totalByteCombine.length);
        System.out.println("Content sent successfully");




        //HERE IS THE ISSUE 
        // I am supposed to receive something from Python Side
        InputStream socketInput = socket.getInputStream();
        String messagetype = socketInput.readUTF();
        System.out.println(messagetype);



    }



    public static void main(String[] args) throws Exception {

        // Must Be 16 Bytes
        String passphrase = "abcdefghijklmnop";

        Discovery client = new Discovery();
        byte[] encryption = client.encryption(passphrase);
        client.sendEncryption(encryption);

    }
}

Python(服务器):

问题位于: def loopCommand()

import socket
import ssl
import hashlib
import os
from Crypto.Cipher import AES
import hashlib
from Crypto import Random 

sHost = ''
sPort = 1234


def bindSocket():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #IPv4 and TCP
    try:
        s.bind((sHost,sPort))
        print("Socket created and binded")
    except socket.error as msgError:
        print(msgError)
        print("Error in Binding Socket")
    return s #so that we can use it


def socketConnect():
    s.listen(1) #listen to 1 connection at a time


    while True:
        try:
            conn, address = s.accept() #Accept connection from client
            print ("Connected to: " + address[0] + ":" +str(address[1]))
        except socket.error as error:
            print ("Error: {0}" .format(e))
            print ("Unable to start socket")
        return conn


def decrypt(str):
    key ="1234567890123456"
    key = key.encode('utf-8')

    decipher = AES.new(key[:16])

    decrypt = decipher.decrypt(str[:16])

    print("it works")

    return decrypt.decode('utf-8')

def encrypt(str):
    key ="1234567890123456"
    key = bytes(key,'utf-8')
    cipher =AES.new(key)
    encrypt = cipher.encrypt(str)

    return encrypt



def loopCommand(conn):
    while True:
        passphrase = "abcdefghijklmnop"
        data = conn.recv(1024)#receive the message sent by client

        if decrypt(data) == passphrase:
            print("Passphrase is the same, generating new passphrase for Client Checking")


            #This is the part where I send it to JAVA

            newPassphrase = "serversocket1234"
            newEncrypt = encrypt(newPassphrase)
            print(type(newEncrypt))            
            conn.send(newEncrypt)
            print("Another passphrase sent")

        else:
            error = "Wrong passphrase"
            rst = "RST"
            print(error)
            conn.send(rst.encode('utf-8'))

        print("DONE")




s = bindSocket()

while True:
    try:
        conn = socketConnect()
        loopCommand(conn)
    except:
        pass

0 个答案:

没有答案