如何打包/加密/解压缩/解密Java中的一堆文件?

Dan*_*anM 3 java encryption zip jsp archive

我本质上是尝试在Java/JSP驱动的网站上执行以下操作:

  • 用户提供密码
  • 密码用于构建包含文本文件的强加密存档文件(zip或其他任何内容)以及存储在服务器上的许多二进制文件.它本质上是用户文件和设置的备份.
  • 之后,用户可以上传文件,提供原始密码,网站将解密和解压缩存档,将提取的二进制文件保存到服务器上的相应文件夹,然后读取文本文件,以便网站可以恢复用户的有关二进制文件的旧设置和元数据.

它是构建/加密存档,然后提取其内容,我正试图弄清楚如何做.我真的不关心存档格式,除了它非常安全.

我的问题的理想解决方案将非常容易实现,并且只需要经过试验和测试的免费和非限制性许可证库(例如apache,berkeley,lgpl).

我知道TrueZIP和WinZipAES库; 前者看起来像是大规模的矫枉过正,我不知道后者是多么稳定......是否有其他解决方案能够奏效?

Kev*_*vin 6

如果您知道如何使用java.util.zip包创建zip文件,则可以创建PBE 密码并将其传递给CipherOutputStream或CipherInputStream(取决于您是否正在读取或写入).

以下内容可以帮助您入门:

public class ZipTest {

    public static void main(String [] args) throws Exception {
        String password = "password";
        write(password);
        read(password);
    }

    private static void write(String password) throws Exception {
        OutputStream target = new FileOutputStream("out.zip");
        target = new CipherOutputStream(target, createCipher(Cipher.ENCRYPT_MODE, password));
        ZipOutputStream output = new ZipOutputStream(target);

        ZipEntry e = new ZipEntry("filename");
        output.putNextEntry(e);
        output.write("helloWorld".getBytes());
        output.closeEntry();

        e = new ZipEntry("filename1");
        output.putNextEntry(e);
        output.write("helloWorld1".getBytes());
        output.closeEntry();

        output.finish();
        output.flush();
    }

    private static Cipher createCipher(int mode, String password) throws Exception {
        String alg = "PBEWithSHA1AndDESede"; //BouncyCastle has better algorithms
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(mode, secretKey, new PBEParameterSpec("saltsalt".getBytes(), 2000));

        return cipher;
    }

    private static void read(String password) throws Exception {
        InputStream target = new FileInputStream("out.zip");
        target = new CipherInputStream(target, createCipher(Cipher.DECRYPT_MODE, password));
        ZipInputStream input = new ZipInputStream(target);
        ZipEntry entry = input.getNextEntry();
        while (entry != null) {
            System.out.println("Entry: "+entry.getName());
            System.out.println("Contents: "+toString(input));
            input.closeEntry();
            entry = input.getNextEntry();
        }
    }

    private static String toString(InputStream input) throws Exception {
        byte [] data = new byte[1024];
        StringBuilder result = new StringBuilder();

        int bytesRead = input.read(data);
        while (bytesRead != -1) {
            result.append(new String(data, 0, bytesRead));
            bytesRead = input.read(data);
        }

        return result.toString();
    } 
}
Run Code Online (Sandbox Code Playgroud)