BadPaddingException:当在两个单独的方法中使用时,密码不起作用

时间:2014-03-27 12:07:15

标签: java encryption

当我使用相同的方法进行加密和解密时,密码可以正常工作,但是只要我将加密的消息发送到服务器(直接发回相同的消息),解密就会抛出一个" BadPaddingException:Data必须以零"开头,有什么想法?

以下是我的decrpytion和加密方法,包括调用它们的方法:

    public byte[] getServerResponse(byte[] message) throws IOException
    {
        Log.debug("Getting server response for: " + message.toString());
        byte[] encMsg = encrypt(message);
        out.write(encMsg);
        out.flush();

        in = new DataInputStream(s.getInputStream());
        byte[] response = new byte[128];
        in.readFully(response);
        byte[] strResponse = decrypt(response);

        Log.debug("Server response: " + response);
        return strResponse;
    }

    private byte[] encrypt(byte[] message) {        
        byte[] encryptedBytes = new byte[128];
        try {                                    
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            encryptedBytes = cipher.doFinal(message);

        } catch (GeneralSecurityException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }               
        return encryptedBytes;
    }

    private byte[] decrypt(byte[] message) {
        byte[] cleartext = new byte[128];
        try {                
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            cleartext = cipher.doFinal(message);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }        
        return cleartext;
    }

密码可供全班使用,初始化如下:

cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

我需要使用IV吗?如果是这样,那怎么做呢?

0 个答案:

没有答案