Example usage for com.lowagie.text.pdf PdfWriter STANDARD_ENCRYPTION_40

List of usage examples for com.lowagie.text.pdf PdfWriter STANDARD_ENCRYPTION_40

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter STANDARD_ENCRYPTION_40.

Prototype

int STANDARD_ENCRYPTION_40

To view the source code for com.lowagie.text.pdf PdfWriter STANDARD_ENCRYPTION_40.

Click Source Link

Document

Type of encryption

Usage

From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java

License:Open Source License

private void setPermissions(cfSession _Session, PDFEncryption _pdfEnc) throws cfmRunTimeException {

    // apply encryption 
    String encryption = getDynamic(_Session, "ENCRYPTION").getString().toLowerCase();
    if (encryption.equals("40") || encryption.equals("40-bit")) {
        _pdfEnc.setEncryptionType(PdfWriter.STANDARD_ENCRYPTION_40);
    } else if (encryption.equals("128") || encryption.equals("128-bit")) {
        _pdfEnc.setEncryptionType(PdfWriter.STANDARD_ENCRYPTION_128);
    } else if (encryption.equals("aes")) {
        _pdfEnc.setEncryptionType(PdfWriter.ENCRYPTION_AES_128);
    } else if (!encryption.equals("none")) {
        throw newRunTimeException(
                "Invalid ENCRYPTION value. Supported values include \"40-bit\", \"128-bit\", \"AES\" and \"none\"");
    }/*from w  ww. j a  va  2  s . c o m*/

    // Default to no permissions
    int permissionsMask = 0;

    if (containsAttribute("PERMISSIONS")) {

        String[] permissions = getDynamic(_Session, "PERMISSIONS").getString().toLowerCase().split(",");
        if (permissions.length > 0) {

            for (int i = 0; i < permissions.length; i++) {
                String nextPermission = permissions[i];
                if (nextPermission.equals("allowprinting")) {
                    permissionsMask |= PdfWriter.ALLOW_PRINTING;
                } else if (nextPermission.equals("allowmodifycontents")) {
                    permissionsMask |= PdfWriter.ALLOW_MODIFY_CONTENTS;
                } else if (nextPermission.equals("allowcopy")) {
                    permissionsMask |= PdfWriter.ALLOW_COPY;
                } else if (nextPermission.equals("allowmodifyannotations")) {
                    permissionsMask |= PdfWriter.ALLOW_MODIFY_ANNOTATIONS;
                } else if (nextPermission.equals("allowscreenreaders")) {
                    if (_pdfEnc.getEncryptionType() == PdfWriter.STANDARD_ENCRYPTION_40)
                        throw newRunTimeException("AllowScreenReaders is not valid with 40-bit encryption");
                    permissionsMask |= PdfWriter.ALLOW_SCREENREADERS;
                } else if (nextPermission.equals("allowassembly")) {
                    if (_pdfEnc.getEncryptionType() == PdfWriter.STANDARD_ENCRYPTION_40)
                        throw newRunTimeException("AllowAssembly is not valid with 40-bit encryption");
                    permissionsMask |= PdfWriter.ALLOW_ASSEMBLY;
                } else if (nextPermission.equals("allowdegradedprinting")) {
                    if (_pdfEnc.getEncryptionType() == PdfWriter.STANDARD_ENCRYPTION_40)
                        throw newRunTimeException("AllowDegradedPrinting is not valid with 40-bit encryption");
                    permissionsMask |= PdfWriter.ALLOW_DEGRADED_PRINTING;
                } else if (nextPermission.equals("allowfillin")) {
                    if (_pdfEnc.getEncryptionType() == PdfWriter.STANDARD_ENCRYPTION_40)
                        throw newRunTimeException("AllowFillIn is not valid with 40-bit encryption");
                    permissionsMask |= PdfWriter.ALLOW_FILL_IN;
                } else {
                    throw newRunTimeException("Invalid permissions value: " + nextPermission);
                }
            }
        }
    }

    // Set the allowed permissions
    _pdfEnc.setAllowedPrivileges(permissionsMask);

    if (containsAttribute("OWNERPASSWORD"))
        _pdfEnc.setOwnerPassword(getDynamic(_Session, "OWNERPASSWORD").getString().getBytes());

    if (containsAttribute("USERPASSWORD"))
        _pdfEnc.setUserPassword(getDynamic(_Session, "USERPASSWORD").getString().getBytes());

}

From source file:org.pdfsam.console.business.pdf.handlers.EncryptCmdExecutor.java

License:Open Source License

public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {

    if ((parsedCommand != null) && (parsedCommand instanceof EncryptParsedCommand)) {

        EncryptParsedCommand inputCommand = (EncryptParsedCommand) parsedCommand;
        setPercentageOfWorkDone(0);/*from w  ww .  ja  v  a2  s  . c om*/
        int encType = PdfWriter.STANDARD_ENCRYPTION_40;
        PrefixParser prefixParser;
        try {
            PdfFile[] fileList = arraysConcat(inputCommand.getInputFileList(),
                    getPdfFiles(inputCommand.getInputDirectory()));
            // check if empty
            if (fileList == null || !(fileList.length > 0)) {
                throw new EncryptException(EncryptException.CMD_NO_INPUT_FILE);
            }
            for (int i = 0; i < fileList.length; i++) {
                try {
                    // set the encryption type
                    if (EncryptParsedCommand.E_AES_128.equals(inputCommand.getEncryptionType())) {
                        encType = PdfWriter.ENCRYPTION_AES_128;
                    } else if (EncryptParsedCommand.E_RC4_128.equals(inputCommand.getEncryptionType())) {
                        encType = PdfWriter.STANDARD_ENCRYPTION_128;
                    }

                    prefixParser = new PrefixParser(inputCommand.getOutputFilesPrefix(),
                            fileList[i].getFile().getName());
                    File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
                    pdfReader = PdfUtility.readerFor(fileList[i]);
                    pdfReader.removeUnusedObjects();
                    pdfReader.consolidateNamedDestinations();

                    // version
                    LOG.debug("Creating a new document.");
                    Character pdfVersion = inputCommand.getOutputPdfVersion();
                    if (pdfVersion != null) {
                        pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmpFile),
                                inputCommand.getOutputPdfVersion().charValue());
                    } else {
                        pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmpFile),
                                pdfReader.getPdfVersion());
                    }

                    HashMap meta = pdfReader.getInfo();
                    meta.put("Creator", ConsoleServicesFacade.CREATOR);

                    setCompressionSettingOnStamper(inputCommand, pdfStamper);

                    pdfStamper.setMoreInfo(meta);
                    pdfStamper.setEncryption(encType, inputCommand.getUserPwd(), inputCommand.getOwnerPwd(),
                            inputCommand.getPermissions());
                    pdfStamper.close();
                    pdfReader.close();
                    File outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName());
                    FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
                    LOG.debug("Encrypted file " + outFile.getCanonicalPath() + " created.");
                    setPercentageOfWorkDone(((i + 1) * WorkDoneDataModel.MAX_PERGENTAGE) / fileList.length);
                } catch (Exception e) {
                    LOG.error("Error encrypting file " + fileList[i].getFile().getName(), e);
                }
            }
            LOG.info("Pdf files encrypted in " + inputCommand.getOutputFile().getAbsolutePath() + ".");
            LOG.info("Permissions: " + PdfEncryptor.getPermissionsVerbose(inputCommand.getPermissions()) + ".");
        } catch (Exception e) {
            throw new EncryptException(e);
        } finally {
            setWorkCompleted();
        }
    } else {
        throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND);
    }
}

From source file:org.pdfsam.guiclient.commons.business.loaders.callable.AddPdfDocument.java

License:Open Source License

/**
* 
* @param fileToAdd file to add/* ww w  .  j a v a  2  s .  c  o  m*/
* @param password password to open the file
* @return the item to add to the table
*/
PdfSelectionTableItem getPdfSelectionTableItem(File fileToAdd, String password, String pageSelection) {
    PdfSelectionTableItem tableItem = null;
    PdfReader pdfReader = null;
    if (fileToAdd != null) {
        tableItem = new PdfSelectionTableItem();
        tableItem.setInputFile(fileToAdd);
        tableItem.setPassword(password);
        tableItem.setPageSelection(pageSelection);
        try {
            //fix 04/11/08 for memory usage
            pdfReader = new PdfReader(new RandomAccessFileOrArray(fileToAdd.getAbsolutePath()),
                    (password != null) ? password.getBytes() : null);
            tableItem.setEncrypted(pdfReader.isEncrypted());
            tableItem.setFullPermission(pdfReader.isOpenedWithFullPermissions());
            if (tableItem.isEncrypted()) {
                tableItem.setPermissions(getPermissionsVerbose(pdfReader.getPermissions()));
                int cMode = pdfReader.getCryptoMode();
                switch (cMode) {
                case PdfWriter.STANDARD_ENCRYPTION_40:
                    tableItem.setEncryptionAlgorithm(EncryptionUtility.RC4_40);
                    break;
                case PdfWriter.STANDARD_ENCRYPTION_128:
                    tableItem.setEncryptionAlgorithm(EncryptionUtility.RC4_128);
                    break;
                case PdfWriter.ENCRYPTION_AES_128:
                    tableItem.setEncryptionAlgorithm(EncryptionUtility.AES_128);
                    break;
                default:
                    break;
                }
            }
            tableItem.setPagesNumber(Integer.toString(pdfReader.getNumberOfPages()));
            tableItem.setFileSize(fileToAdd.length());
            tableItem.setPdfVersion(pdfReader.getPdfVersion());
            tableItem.setSyntaxErrors(pdfReader.isRebuilt());
            initTableItemDocumentData(pdfReader, tableItem);
        } catch (Exception e) {
            tableItem.setLoadedWithErrors(true);
            LOG.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                    "Error loading ") + fileToAdd.getAbsolutePath() + " :", e);
        } finally {
            if (pdfReader != null) {
                pdfReader.close();
                pdfReader = null;
            }
        }
    }
    return tableItem;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfDocumentWriter.java

License:Open Source License

public void open() throws DocumentException {
    this.document = new Document();
    // pageSize, marginLeft, marginRight, marginTop, marginBottom));

    writer = PdfWriter.getInstance(document, out);
    writer.setLinearPageMode();/*from  w  w w .j  ava2s.  c  om*/

    version = getVersion();
    writer.setPdfVersion(version);
    writer.setViewerPreferences(getViewerPreferences());

    final String encrypt = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.Encryption");

    if (encrypt != null) {
        if (encrypt.equals(PdfPageableModule.SECURITY_ENCRYPTION_128BIT) == true
                || encrypt.equals(PdfPageableModule.SECURITY_ENCRYPTION_40BIT) == true) {
            final String userpassword = config.getConfigProperty(
                    "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.UserPassword");
            final String ownerpassword = config.getConfigProperty(
                    "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.OwnerPassword");
            // Log.debug ("UserPassword: " + userpassword + " - OwnerPassword: " + ownerpassword);
            final byte[] userpasswordbytes = DocWriter.getISOBytes(userpassword);
            byte[] ownerpasswordbytes = DocWriter.getISOBytes(ownerpassword);
            if (ownerpasswordbytes == null) {
                ownerpasswordbytes = PdfDocumentWriter.PDF_PASSWORD_PAD;
            }
            final int encryptionType;
            if (encrypt.equals(PdfPageableModule.SECURITY_ENCRYPTION_128BIT)) {
                encryptionType = PdfWriter.STANDARD_ENCRYPTION_128;
            } else {
                encryptionType = PdfWriter.STANDARD_ENCRYPTION_40;
            }
            writer.setEncryption(userpasswordbytes, ownerpasswordbytes, getPermissions(), encryptionType);
        }
    }

    /**
     * MetaData can be set when the writer is registered to the document.
     */
    final String title = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.Title",
            config.getConfigProperty("org.pentaho.reporting.engine.classic.core.metadata.Title"));
    final String subject = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.Description",
            config.getConfigProperty("org.pentaho.reporting.engine.classic.core.metadata.Description"));
    final String author = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.Author",
            config.getConfigProperty("org.pentaho.reporting.engine.classic.core.metadata.Author"));
    final String keyWords = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.Keywords",
            config.getConfigProperty("org.pentaho.reporting.engine.classic.core.metadata.Keywords"));

    if (title != null) {
        document.addTitle(title);
    }
    if (author != null) {
        document.addAuthor(author);
    }
    if (keyWords != null) {
        document.addKeywords(keyWords);
    }
    if (keyWords != null) {
        document.addSubject(subject);
    }

    document.addCreator(PdfDocumentWriter.CREATOR);
    document.addCreationDate();

    // getDocument().open();
    awaitOpenDocument = true;
}

From source file:org.sejda.impl.itext.util.EncryptionUtils.java

License:Apache License

/**
 * Mapping between Sejda and iText encryption algorithms
 * /*from w  w  w  .ja  va2 s .  co  m*/
 * @param encryption
 * @return the iText encryption constant
 */
public static int getEncryptionAlgorithm(PdfEncryption encryption) {
    switch (encryption) {
    case AES_ENC_128:
        return PdfWriter.ENCRYPTION_AES_128;
    case STANDARD_ENC_128:
        return PdfWriter.STANDARD_ENCRYPTION_128;
    default:
        return PdfWriter.STANDARD_ENCRYPTION_40;
    }
}