如何用文件实现加密和解密类对象?

时间:2016-05-29 05:17:49

标签: java encryption

我想用类对象加密文件。类对象描述文件内容。

在Java 1.7更新51中没有填充的同一组代码工作正常。当我转移到几乎没有安全更新的Java 1.7更新79时,我收到了与加密填充相关的错误。

添加填充支持后,无法检索类对象。 readObject()中的decryptFile()会因InvalidClassException不匹配而导致serialVersionUID。序列ID相同,但无法正确检索。

文件加密和解密在没有类对象的情况下正常工作。如何在带有填充的文件中使用类对象实现加密和解密?

我使用固定的AES密钥并验证密钥和IV以进行加密和解密。

public void encryptFile(FileInfo fileInfo, File inFile, File outFile)
        throws Exception {

    //aesCipher = Cipher.getInstance("AES");
    aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    aeskeySpec = new SecretKeySpec(aesKey, "AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
    aesIV = aesCipher.getIV();

    FileInputStream is = new FileInputStream(inFile);
    CipherOutputStream os = new CipherOutputStream(new FileOutputStream(outFile),
            aesCipher);

    ObjectOutputStream objStream = new ObjectOutputStream(os);

    // File info class object is written
    objStream.writeObject(fileInfo);

    copy(is, os);

    is.close();
    os.close();
}

public void decryptFile(File inFile, File outFile)
        throws Exception {

    //aesCipher = Cipher.getInstance("AES");
    aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    aeskeySpec = new SecretKeySpec(aesKey, "AES");
    aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec, new IvParameterSpec(aesIV));

    CipherInputStream is = new CipherInputStream(new FileInputStream(inFile),
            aesCipher);
    FileOutputStream os = new FileOutputStream(outFile);

    MutableObjectClass objStream = new MutableObjectClass(is, FileInfo.class);
    FileInfo fileInfo = (FileInfo) objStream.readObject();

    //Refer file info object

    copy(is, os);

    is.close();
    os.close();
}

MutableObjectClass.java文件。

class MutableObjectClass extends ObjectInputStream {
    String className;

    public MutableObjectClass(InputStream in, Class<?> cls)
            throws Exception {
        super(in);
        this.className = cls.getName();
    }

    @Override
    protected ObjectStreamClass readClassDescriptor()
            throws Exception {

        ObjectStreamClass cd = super.readClassDescriptor();
        try {
            Field f = cd.getClass().getDeclaredField("name");
            f.setAccessible(true);
            f.set(cd, className);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return cd;
    }

0 个答案:

没有答案