发送字符串由TCP上的密钥编码使用Windows流BadPaddingException

时间:2013-05-21 03:37:00

标签: java windows tcp encryption

我认为我遇到了一个特定于Windows操作系统(Windows 7)的问题,使用writeUTF()和readUTF()方法通过TCP连接发送加密字符串。

客户端和服务器首先使用私钥 - 公钥对建立连接。然后他们就用于进一步通信的共享密钥达成一致。当由共享密钥加密并通过writeUTF()和readUTF()发送的字符串具有错误的填充时,会出现问题。发生的第一个实例是发送使用writeUTF()方法从服务器到客户端的加密确认。

问题有时只会发生!有时程序运行顺利,没有错误,但是有时会抛出BadPaddingException,说明客户端的“给定最终块没有正确填充”:

            byte[] byteDecriptedAck = decryptCipher.doFinal(encryptedAck.getBytes());

和服务器端:

            byte[] byteDecriptedAck = decryptCipher.doFinal(encryptedPassword.getBytes());

在OSX操作系统上运行代码时不会出现此问题。因此,我认为它与windows如何表示UTF字符串,写入UTF字符串或读取UTF字符串有关。

我因试图解决这个问题而感到茫然。非常感谢任何帮助。

由于

建立连接客户端的代码:

private void establishConnection() {
    try {
        int numBytesPubKey = in.readInt();
        byte[] bytesPubKey = new byte[numBytesPubKey];
        in.readFully(bytesPubKey, 0, numBytesPubKey);

        //get public key from server
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytesPubKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

        //generate secret key for communicating
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); //key size
        SecretKey secretKey = keyGen.generateKey();
        byte[] encodedSecretKey = secretKey.getEncoded();

        //use public key to encode message containing secret key to send to server
        encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherData = encryptCipher.doFinal(encodedSecretKey);

        //send secret key to server encoded by servers public key
        out.writeInt(cipherData.length);
        out.write(cipherData, 0, cipherData.length);

        //read acknowledge from server
        SecretKeySpec secretKeySpec = new SecretKeySpec(encodedSecretKey,"AES");

        String encryptedAck = in.readUTF();
        decryptCipher = Cipher.getInstance("AES");
        decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] byteDecriptedAck = decryptCipher.doFinal(encryptedAck.getBytes());

        if(!(new String(byteDecriptedAck).equals("ACK"))) {
            System.err.println("Server acknowledgement corrupted. Terminate communications.");
            System.exit(1);
        }

        //send password to server

        encryptCipher = Cipher.getInstance("AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] cipheredPassword = encryptCipher.doFinal("password".getBytes());
        out.writeUTF(new String(cipheredPassword));

    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    }
}

建立连接服务器端的代码:

private void establishConnection() {
    try {
        //generate public/private key pair for communicating with initially
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(1024, random);

        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey privKey = pair.getPrivate();
        PublicKey pubKey = pair.getPublic();

        //send public key to client
        byte[] bytesPubKey = pubKey.getEncoded();
        out.writeInt(bytesPubKey.length);
        out.write(bytesPubKey, 0, bytesPubKey.length);

        //read in secret key to use for further communications
        int numBytesSecretKey = in.readInt();
        byte[] bytesSecretKey = new byte[numBytesSecretKey];
        in.readFully(bytesSecretKey, 0, numBytesSecretKey);

        decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, privKey, decryptCipher.getParameters());
        byte[] byteDecriptedSecretKey = decryptCipher.doFinal(bytesSecretKey);
        SecretKeySpec secretKeySpec = new SecretKeySpec(byteDecriptedSecretKey,"AES");

        //send back acknowledgment encoded with secret key: ACK
        encryptCipher = Cipher.getInstance("AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] cipheredACK = encryptCipher.doFinal("ACK".getBytes());

        out.writeUTF(new String(cipheredACK));

        //read password from client
        String encryptedPassword = in.readUTF();
        decryptCipher = Cipher.getInstance("AES");
        decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] byteDecriptedAck = decryptCipher.doFinal(encryptedPassword.getBytes());

        if(!(new String(byteDecriptedAck).equals("password"))) {
            System.err.println("Access Denied. Client password incorrect. Terminate communications.");
            System.exit(1);
        } else {
            System.err.println("Access Granted.");
        } 
    } catch (Exception e) {
        e.printStackTrace();
    }
} 

1 个答案:

答案 0 :(得分:1)

byte[] cipheredACK = encryptCipher.doFinal("ACK".getBytes());
out.writeUTF(new String(cipheredACK));

那不行。 UTF和String用于字符数据。这里有原始字节,不能解释为文本。

将它们作为二进制数据发送:

out.write(cipheredACK);

您看到OS X和Windows之间存在差异的原因是您在将字节强制转换为字符串时未指定字符编码,因此它变为特定于平台的。如果这确实是字符数据,则将字符集传递给构造函数以使其与平台无关。但在你的情况下,它不是字符数据,所以只需要字节。

另外,为什么不使用SSL?