如何确保DES加密中的正确填充?

时间:2017-04-07 05:25:40

标签: java sockets encryption des

我正在尝试实现一个基本的Diffie-Hellman协议,并且代码成功到需要使用DES解密发送的值时。我看了很多例子,其中关键是不匹配,但我在连接的两端打印它们的值,它们都完全相同。我还尝试了多种填充方案以及更改密钥的生成方式。

我的最后一次尝试是将参数IvParameterSpec添加到密码init,但这只解决了其中一个错误。

我在一台机器上运行它,其中套接字通过localhost连接,我一直在检查任何一方的问题,发送的数据与接收的数据不完全匹配,但发送中没有任何改变。但是,我注意到,当打印套接字两侧的每个字节数组时,客户端比服务器长得多,看起来像是填充(?)

我得到的错误是说最后一个块填充不正确,因此解密失败

我的服务器代码(未按预期工作的一方):

public static void main(String[] args) {
    ServerSocket welcomeSocket = null;

    // Creates a connectable socket on port 6789
    try {
        welcomeSocket = new ServerSocket(6789);
    } catch (IOException e) {
        e.printStackTrace();
    }
    while(true){
        try{
            double k2, B, A;
            double n = 13;
            double g = 61;
            long y = 7;
            B = (Math.pow(g, y))%n;

            System.out.println("Accepting connections");
            // Accept an incoming connection on the socket server
            Socket connectionSocket = welcomeSocket.accept();
            // Creates a read and write stream for that client
            DataInputStream inFromClient = new DataInputStream(connectionSocket.getInputStream());
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

            // Sends the double to the client
            outToClient.writeDouble(B);
            System.out.println("Sent " + B);
            // Reads the number sent by the Client
            A = inFromClient.readDouble();
            System.out.println("Received " + A);

            // Modifies the number
            k2 = (Math.pow(A, y))%n;
            System.out.println("DES key seed = " + k2);
            byte[] deskeydata = toByteArray(k2);

            // Turns the bytes of the modified number into a DES key spec
            DESKeySpec deskeyspec = new DESKeySpec(deskeydata);

            // Makes a secret key (DES)
            SecretKeyFactory keyF = SecretKeyFactory.getInstance("DES");
            SecretKey keystuff = keyF.generateSecret(deskeyspec);
            System.out.println(keystuff.toString());

            // Gets an incoming string from the client and turns it into binary
            byte[] incomingBytes = new byte[128];
            try{
                inFromClient.readFully(incomingBytes);
            } catch(EOFException eof){
                System.out.println("Finished reading");
            }
            System.out.println(new String(incomingBytes));
            Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

            // Decrypts the string using the shared secret key
            c.init(Cipher.DECRYPT_MODE, keystuff, new IvParameterSpec(new byte[8]));
            byte[] ct2 = c.doFinal(incomingBytes);

            // Decode it from base 64
            //byte[] decodedBytes = Base64.getDecoder().decode(ct2);

            // Prints the received string
            System.out.println("Received: " + new String(ct2));

            inFromClient.close();
            outToClient.close();

        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

我的客户代码:

public static void main(String[] args) {

    // Creates a socket to the local host on port 6789
    Socket clientSocket = null;
    try {
        clientSocket = new Socket("localhost", 6789);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try{
        double k1, B, A;
        double n = 13;
        double g = 61;
        long x = 3;

        // Sends an unencrypted number to the server
        A = (Math.pow(g, x))%n;
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());  

        // Transforms A into a byte array and sends it over
        outToServer.writeDouble(A);
        outToServer.flush();
        System.out.println("Sending " + A);

        // Reads the incoming data from the server
        B = inFromServer.readDouble();
        System.out.println("Recieved " + B);

        // Modifies the data to create the number for des key
        k1 = (Math.pow(B, x))%n;
        System.out.println("DES key seed = " + k1);
        byte[] deskeydata = toByteArray(k1);

        // Turns the bytes of the modified number into a DES key spec
        DESKeySpec deskeyspec = new DESKeySpec(deskeydata);

        // Makes a secret key (DES)
        SecretKeyFactory keyF = SecretKeyFactory.getInstance("DES");
        SecretKey keystuff = keyF.generateSecret(deskeyspec);
        System.out.println(keystuff.toString());

        // Takes in input from the user and turns it into binary
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a message:");

        String sentence = inFromUser.readLine();
        byte[] str2 = sentence.getBytes();
        byte[] encodedMessage = Base64.getEncoder().encode(str2);

        Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

        // Encrypts the user's input with the secret key
        c.init(Cipher.ENCRYPT_MODE, keystuff, new IvParameterSpec(new byte[8]));
        byte[] ct2 = c.doFinal(encodedMessage);
        System.out.println("Initted the cipher and moving forward with " + new String(ct2));

        // Writes the encrypted message to the user
        outToServer.write(ct2);
        outToServer.flush();


        inFromServer.close();
        outToServer.close();
    } catch(Exception e){
        e.printStackTrace();
    }

}

任何可以帮助我完成这项工作的事情都会受到极大的欢迎,因为我已经在这段时间里独自处理这个错误。

1 个答案:

答案 0 :(得分:0)

我设法找到了解决这个问题的方法(虽然我怀疑这是非常低效的)。问题是由于服务器端的readFully方法。我正在将答案读入一个128字节的数组,解密函数将字节数组中的空插槽视为一些东西而不是什么。

为了解决这个问题,我用以下内容替换了输入部分,它读取每个字节并创建一个字节数组,其中包含传入消息的确切长度。

<TextBox x:Name="TextBox1" Margin="16,16,16,49" TextWrapping="Wrap"
                 IsReadOnly="True" VerticalScrollBarVisibility="Auto" FontSize="12" />

<Slider x:Name="slider" HorizontalAlignment="Left" Margin="20,78,0,-1"
            Width="166" Maximum="50" Minimum="12" Value="{Binding Path=FontSize, ElementName=TextBox1}" />