Java:无效的类型代码05 / a Socket的OutputStream

时间:2016-05-31 15:15:57

标签: java encryption aes

我正在尝试加密Socket的ObjectOutputStream。但不知何故,当我尝试解密/加密它时,我得到一个 java.io.StreamCorruptedException

我的加密/解密方法:(那些方法不是我的,我在stackoverflow上找到它们)

/**
 * Encrypt a object and write it to the given outstream
 * @param object the serializable object
 * @param ostream The outstream
 */
private void encrypt(Serializable object, OutputStream ostream) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    try {
        SecretKeySpec sks = new SecretKeySpec(key, transformation);

        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        SealedObject sealedObject = new SealedObject(object, cipher);

        CipherOutputStream cos = new CipherOutputStream(ostream, cipher);
        @SuppressWarnings("resource")
        ObjectOutputStream outputStream = new ObjectOutputStream(cos);
        outputStream.writeObject(sealedObject);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }
}

/**
 * Decrypt a object from the given InputStream
 * @param istream the inputstream
 * @return the decrypted object
 */
private Object decrypt(InputStream istream) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    SecretKeySpec sks = new SecretKeySpec(key, transformation);
    Cipher cipher = Cipher.getInstance(transformation);
    cipher.init(Cipher.DECRYPT_MODE, sks);

    CipherInputStream cipherInputStream = new CipherInputStream(istream, cipher);
    @SuppressWarnings("resource")
    ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
    SealedObject sealedObject;
    try {
        sealedObject = (SealedObject) inputStream.readObject();
        return sealedObject.getObject(cipher);
    } catch (ClassNotFoundException | IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
        return null;
    }

}

所以我尝试了,我也看了我的问题,我发现它与重复的 ObjectOutputStream 有关,但我怎么能从 CipherOutputStream ,无需创建新的 ObjectOutputStream /从 CipherInputStream 读取我的对象而不创建新的 ObjectInputStream

0 个答案:

没有答案