xuchuanyin / workbench

0 stars 0 forks source link

2020年12月20日 加密excel打开 #101

Open xuchuanyin opened 3 years ago

xuchuanyin commented 3 years ago
package ind.chuanyin.excel;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;

public class PwdTest {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("should specify the file path");
            System.exit(-1);
        }

        for (int i = 0; i < args.length; i++) {
            String excelPath = args[i];
            for (int j = 0; j < 10000; j++) {
                String pwd = String.format("%04d", j);
                boolean rtn = false;
                try {
                    rtn = openExcelUsingPwd(excelPath, pwd);
                } catch (IOException | GeneralSecurityException e) {
                    e.printStackTrace();
                }

                if (rtn) {
                    System.out.println("password for " + excelPath + " is " + pwd);
                    break;
                } else if (j % 100 == 0){
                    System.out.println(j);
                }
            }
        }
        System.exit(0);
    }

    private static boolean openExcelUsingPwd(String excelPath, String pwd) throws IOException, GeneralSecurityException {
        InputStream is = null;
        try {
            is = new FileInputStream(excelPath);
            POIFSFileSystem pfs = new POIFSFileSystem(is);
            Biff8EncryptionKey.setCurrentUserPassword(pwd);

            EncryptionInfo encryptionInfo = new EncryptionInfo(pfs);
            Decryptor decryptor = Decryptor.getInstance(encryptionInfo);
            return decryptor.verifyPassword(pwd);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}