解压密码已知的zip文件

第一步:剥去密码:

下面方法是解密工作,参数:

srcFile:源文件地址
destfile:解密后的临时文件
pwd:密码

 

public static void decrypt(String srcFile, String destfile, String pwd) throws Exception {
        SecureRandom sr = new SecureRandom();
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        DESKeySpec dks = new DESKeySpec(padding(Base64.encode(pwd.getBytes())));
        SecretKey securekey = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        InputStream is = new FileInputStream(srcFile);
        OutputStream out = new FileOutputStream(destfile);
        CipherOutputStream cos = new CipherOutputStream(out, cipher);
        byte[] buffer = new byte[1024];

        byte[] pwdByte = new byte[20];
        int len = is.read(pwdByte);
        byte[] hashByte = DigisterUtil.getHashEncode(pwd.getBytes());

        if (len != 20 || hashByte.length != 20) {
            throw new RuntimeException("密码错误");
        }
        for (int i = 0; i < 20; i++) {
            if (pwdByte[i] != hashByte[i]) {
                throw new RuntimeException("密码错误");
            }
        }

        int r;
        while ((r = is.read(buffer)) >= 0) {
            cos.write(buffer, 0, r);
        }
        cos.close();
        out.close();
        is.close();
    }

 第二步:用ZipFile和ZipEntry解压缩文件:

 

ZipFile zipFile = new ZipFile(上面的临时文件);
Enumeration entryEnu = zipFile.entries(); 
while (entryEnu.hasMoreElements()) { 
    ZipEntry entry = (ZipEntry) entryEnu.nextElement();
    is = zipFile.getInputStream(entry); 
    bos = new ByteArrayOutputStream(is.available());
    byte[] buff = new byte[8192]; int len = 0;
    while ((len = is.read(buff)) != -1) {
         bos.write(buff, 0, len); 
    } 
    bis = new ByteArrayInputStream(bos.toByteArray()); 
    break; 
}
temp.delete(); 
 

 

 

你可能感兴趣的:(zip)