public RecordInputStream createDecryptingStream(InputStream original) {
      FilePassRecord fpr = _filePassRec;
      String userPassword = Biff8EncryptionKey.getCurrentUserPassword();

      Biff8EncryptionKey key;
      if (userPassword == null) {
        key = Biff8EncryptionKey.create(fpr.getDocId());
      } else {
        key = Biff8EncryptionKey.create(userPassword, fpr.getDocId());
      }
      if (!key.validate(fpr.getSaltData(), fpr.getSaltHash())) {
        throw new EncryptedDocumentException(
            (userPassword == null ? "Default" : "Supplied")
                + " password is invalid for docId/saltData/saltHash");
      }
      return new RecordInputStream(original, key, _initialRecordsSize);
    }
Example #2
0
  /** Creates a Workbook from the given NPOIFSFileSystem, which may be password protected */
  private static Workbook create(NPOIFSFileSystem fs, String password)
      throws IOException, InvalidFormatException {
    DirectoryNode root = fs.getRoot();

    // Encrypted OOXML files go inside OLE2 containers, is this one?
    if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
      EncryptionInfo info = new EncryptionInfo(fs);
      Decryptor d = Decryptor.getInstance(info);

      boolean passwordCorrect = false;
      InputStream stream = null;
      try {
        if (password != null && d.verifyPassword(password)) {
          passwordCorrect = true;
        }
        if (!passwordCorrect && d.verifyPassword(Decryptor.DEFAULT_PASSWORD)) {
          passwordCorrect = true;
        }
        if (passwordCorrect) {
          stream = d.getDataStream(root);
        }
      } catch (GeneralSecurityException e) {
        throw new IOException(e);
      }

      if (!passwordCorrect) {
        if (password != null) throw new EncryptedDocumentException("Password incorrect");
        else
          throw new EncryptedDocumentException(
              "The supplied spreadsheet is protected, but no password was supplied");
      }

      OPCPackage pkg = OPCPackage.open(stream);
      return create(pkg);
    }

    // If we get here, it isn't an encrypted XLSX file
    // So, treat it as a regular HSSF XLS one
    if (password != null) {
      Biff8EncryptionKey.setCurrentUserPassword(password);
    }
    Workbook wb = new HSSFWorkbook(root, true);
    Biff8EncryptionKey.setCurrentUserPassword(null);
    return wb;
  }