Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;//from  www  . j  ava  2 s. co  m
    String contentType;
    String fileExtension;
    IDataStore emailDispatchDataStore;
    String nameSuffix;
    String descriptionSuffix;
    String containedFileName;
    String zipFileName;
    boolean reportNameInSubject;

    logger.debug("IN");
    try {
        parametersMap = dispatchContext.getParametersMap();
        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore();
        nameSuffix = dispatchContext.getNameSuffix();
        descriptionSuffix = dispatchContext.getDescriptionSuffix();
        containedFileName = dispatchContext.getContainedFileName() != null
                && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName()
                        : document.getName();
        zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("")
                ? dispatchContext.getZipMailName()
                : document.getName();
        reportNameInSubject = dispatchContext.isReportNameInSubject();

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = dispatchContext.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = dispatchContext.getMailTxt();

        String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return false;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }

            //session = Session.getDefaultInstance(props, auth);
            session = Session.getInstance(props, auth);
            //session.setDebug(true);
            //session.setDebugOut(null);
            logger.info("Session.getInstance(props, auth)");

        } else {
            //session = Session.getDefaultInstance(props);
            session = Session.getInstance(props);
            logger.info("Session.getInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type

        String subject = mailSubj;

        if (reportNameInSubject) {
            subject += " " + document.getName() + nameSuffix;
        }

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + descriptionSuffix);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = null;
        //if zip requested
        if (dispatchContext.isZipMailDocument()) {
            mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension);
        }
        //else 
        else {
            sds = new SchedulerDataSource(executionOutput, contentType,
                    containedFileName + nameSuffix + fileExtension);
            mbp2.setDataHandler(new DataHandler(sds));
            mbp2.setFileName(sds.getName());
        }

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

/**
 * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
 * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
 * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the
 * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its
 * PublicKey for future payload encryption.
 *
 * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if
 *                                     there is an error creating a self-sign certificate to present to the
 *                                     server (whilst trying to get the CSR signed)
 *///from   w  w w .  j a v a 2s  . co m
public void beginEnrollmentFlow() throws AgentCoreOperationException {
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n");
    }

    PKCS10CertificationRequest certSignRequest = generateCertSignRequest();

    /**
     *  -----------------------------------------------------------------------------------------------
     *  Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request.
     *  In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this.
     *  -----------------------------------------------------------------------------------------------
     */
    X500Name issuer = new X500Name("CN=Temporary Issuer");
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date fromDate = new Date();
    Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L));

    // Build the self-signed cert using BC, sign it with our private key (self-signed)
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate,
            certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo());
    ContentSigner sigGen;
    X509Certificate tmpCert;

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate());
        tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER)
                .getCertificate(certBuilder.build(sigGen));
    } catch (OperatorCreationException e) {
        String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }
    /**
     *  -----------------------------------------------------------------------------------------------
     */

    this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
    this.serverPublicKey = initPublicKeyOfServer();

    storeCertificateToStore(AgentConstants.DEVICE_CERT_ALIAS, SCEPCertificate);
    storeKeyToKeyStore(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, this.privateKey, SCEPCertificate);

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER
                + "SCEPCertificate, DevicePrivateKey, ServerPublicKey was saved to device keystore ["
                + AgentConstants.DEVICE_KEYSTORE + "]");
        log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey()
                + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

/**
 * Gets the connection to the nextpax server and executes the specified request.
 * /*ww  w  .ja v  a  2  s  .  co  m*/
 * @param url the connection URL.
 * @param rq the request object.
 * @return the XML string returned by the message.
 * @throws Throwable the exception thrown by the operation.
 */
private static final String getConnection(String rq) throws Throwable {
    String xmlString = "";
    CustomHttpConnection connection = new CustomHttpConnection();

    //      try {
    LOG.debug("NEXTPAX is using: " + RazorConfig.getNextPaxRequestURL());
    //         URL url = new URL(RazorConfig.getNextPaxRequestURL());
    //         connection = (HttpsURLConnection) url.openConnection();
    //         connection.setRequestMethod("POST");
    //         connection.setDoOutput(true);
    //         connection.setRequestProperty("Content-Type", "application/xml");
    BASE64Encoder enc = new sun.misc.BASE64Encoder();
    Security.addProvider(new BouncyCastleProvider());
    String userpassword = "bookingnet" + ":" + "BAD5PqtE";
    String encodedAuthorization = enc.encode(userpassword.getBytes());
    //         connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
    //         connection.setRequestProperty("Authorization", "Basic " + userpassword);
    xmlString = connection.createPostRequest(RazorConfig.getNextPaxRequestURL(), encodedAuthorization,
            "application/xml", rq);
    //
    //         Provider[] providers = Security.getProviders();
    //         for(int i = 0; i < providers.length; i++) {
    //            LOG.debug(providers[i].getName());
    //         }
    //         
    //         LOG.debug("Request process started");
    //         
    //         if (rq != null) {
    //            LOG.debug("Setting request property");
    //            connection.setRequestProperty("Accept", "application/xml"); // this
    //            LOG.debug("Connecting...");
    //            connection.connect(); // this
    //            LOG.debug("Connected");
    //            byte[] outputBytes = rq.getBytes("UTF-8");
    //            
    //            OutputStream os = connection.getOutputStream();
    //            os.write(outputBytes);
    //            LOG.debug("Writing output");
    //         }
    //
    //         LOG.debug("Check connection response code");
    //         if (connection.getResponseCode() != 200) {
    //            throw new RuntimeException("HTTP:" + connection.getResponseCode() + " URL " + url);
    //         }
    //         BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
    //         String line;
    //         LOG.debug("Reading XML");
    //         while ((line = br.readLine()) != null) {
    //            xmlString += line;
    //         }
    //      } catch (Throwable x) {
    //         LOG.error((x.getMessage()));
    //         x.printStackTrace();
    //         throw new RuntimeException(x.getMessage());
    //      } finally {
    //         if (connection != null) {
    //            connection.disconnect();
    //         }
    //      }
    return xmlString;
}

From source file:org.eatabrick.vecna.Vecna.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from  w w  w . j  a  va 2 s . c  o  m

    settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    adapter = new PasswordEntryAdapter(this);
    adapter.setNotifyOnChange(false);
    setListAdapter(adapter);

    Security.addProvider(new BouncyCastleProvider());

    if (savedInstanceState != null) {
        passphrase = savedInstanceState.getString("passphrase");
        adapter.populate(savedInstanceState.getStringArray("entries"));
        adapter.notifyDataSetChanged();
    }

    getListView().setLongClickable(true);
    getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) {
            onListItemLongClick(parent, v, pos, id);
            return true;
        }
    });
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private RSAPrivateKey readKeyFile() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    String parse[] = readPEMFile(sslKeyFile, KEY_PATTERN, 2);
    if (parse == null)
        throw new IllegalArgumentException("invalid key file contents");

    if (parse[0].length() == 0) { // BEGIN PRIVATE KEY
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(parse[1])));
    }/*w  ww  . j ava 2  s.  co  m*/

    if (parse[0].contains("RSA")) { // BEGIN RSA PRIVATE KEY
        Security.addProvider(new BouncyCastleProvider());

        PEMParser pemParser = new PEMParser(new FileReader(sslKeyFile));
        Object parsedObject = pemParser.readObject();
        if (!(parsedObject instanceof PEMKeyPair))
            throw new IllegalArgumentException("invalid key file contents");

        PEMKeyPair keyPair = (PEMKeyPair) parsedObject;
        RSAPrivateKey privateKey = (RSAPrivateKey) BouncyCastleProvider
                .getPrivateKey(keyPair.getPrivateKeyInfo());
        if (privateKey == null)
            throw new IllegalArgumentException("invalid key file contents");
        return privateKey;
    }

    throw new IllegalArgumentException("invalid key file contents");
}

From source file:org.mule.api.security.tls.TlsConfiguration.java

/**
 * @param anon      If the connection is anonymous then we don't care about client keys
 * @param namespace Namespace to use for global properties (for JSSE use JSSE_NAMESPACE)
 * @throws CreateException ON initialisation problems
 *///from w  ww.ja  va  2  s. c o  m
public void initialise(boolean anon, String namespace) throws CreateException {
    if (logger.isDebugEnabled()) {
        logger.debug("initialising: anon " + anon);
    }
    validate(anon);

    Security.addProvider(provider);
    System.setProperty("java.protocol.handler.pkgs", protocolHandler);

    if (!anon) {
        initKeyManagerFactory();
    }
    initTrustManagerFactory();

    if (null != namespace) {
        new TlsPropertiesMapper(namespace).writeToProperties(System.getProperties(), this);
    }
}

From source file:controller.CCInstance.java

public final ArrayList<CCAlias> loadKeyStoreAndAliases()
        throws LibraryNotLoadedException, KeyStoreNotLoadedException, CertificateException, KeyStoreException,
        LibraryNotFoundException, AliasException {
    String pkcs11config = "name = SmartCard\n library = ";
    String path = null;//from ww  w .  jav a2  s .  com
    if (SystemUtils.IS_OS_WINDOWS) {
        path = System.getenv("HOMEDRIVE") + "\\windows\\system32\\pteidpkcs11.dll";
    } else if (SystemUtils.IS_OS_LINUX) {
        path = "/usr/local/lib/libpteidpkcs11.so";
    } else if (SystemUtils.IS_OS_MAC_OSX) {
        path = "/usr/local/lib/pteidpkcs11.bundle";
    }

    if (null == path) {
        throw new LibraryNotLoadedException(Bundle.getBundle().getString("unknownOS"));
    } else if (new File(path).exists()) {
        pkcs11config += path;
    } else {
        String res = userLoadLibraryPKCS11();
        if (null != res) {
            pkcs11config += res;
        }
        throw new LibraryNotFoundException(Bundle.getBundle().getString("libraryNotFound"));
    }
    final byte[] pkcs11configBytes;
    try {
        pkcs11configBytes = pkcs11config.getBytes();
    } catch (Exception eiie) {
        Logger.getLogger().addEntry(eiie);
        throw new LibraryNotFoundException(Bundle.getBundle().getString("libraryDoesNotExist"));
    }
    final ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11configBytes);
    try {
        pkcs11Provider = new sun.security.pkcs11.SunPKCS11(configStream);
        pkcs11Provider.setCallbackHandler(new CallbackHandler() {

            @Override
            public void handle(javax.security.auth.callback.Callback[] callbacks)
                    throws IOException, UnsupportedCallbackException {
                for (javax.security.auth.callback.Callback c : callbacks) {
                    if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(null);
                    }
                }
            }
        });
    } catch (Exception eiie) {
        Logger.getLogger().addEntry(eiie);
        throw new LibraryNotLoadedException(Bundle.getBundle().getString("libraryNotLoaded"));
    }

    Security.addProvider(pkcs11Provider);

    try {
        pkcs11ks = KeyStore.getInstance("PKCS11");
        pkcs11ks.load(null, null);
    } catch (Exception e) {
        Logger.getLogger().addEntry(e);
        throw new KeyStoreNotLoadedException(Bundle.getBundle().getString("keystoreNotLoaded"));
    }

    final Enumeration aliasesEnum = pkcs11ks.aliases();
    aliasList.clear();

    while (aliasesEnum.hasMoreElements()) {
        final String alias = (String) aliasesEnum.nextElement();
        if (null != alias) {
            if (alias.isEmpty()) {
                throw new AliasException(Bundle.getBundle().getString("blankAlias"));
            } else {
                final Certificate[] certChain = pkcs11ks.getCertificateChain(alias);
                if (null != certChain) {
                    if (CCAlias.ASSINATURA.equals(alias)) {
                        if (0 == certChain.length) {
                            throw new CertificateException(Bundle.getBundle().getString("chainInvalidFormat"));
                        } else {
                            final Certificate cert = certChain[0];
                            try {
                                ((X509Certificate) cert).checkValidity();
                                if (1 <= certChain.length) {
                                    final CCAlias ccAliasTemp = new CCAlias(alias, certChain);
                                    aliasList.add(ccAliasTemp);
                                }
                            } catch (CertificateExpiredException cee) {
                                Logger.getLogger().addEntry(cee);
                                throw new CertificateException(Bundle.getBundle().getString("aliasCertificate")
                                        + " " + alias + " " + Bundle.getBundle().getString("expired") + "!");
                            } catch (CertificateNotYetValidException cee) {
                                Logger.getLogger().addEntry(cee);
                                throw new CertificateException(
                                        Bundle.getBundle().getString("aliasCertificate") + " " + alias + " "
                                                + Bundle.getBundle().getString("notYetValid") + "!");
                            }
                        }
                    }
                }
            }
        }
    }
    return aliasList;
}

From source file:de.brendamour.jpasskit.signing.PKFileBasedSigningUtil.java

private void addBCProvider() {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }

}

From source file:org.cesecore.keys.token.p11.Pkcs11SlotLabel.java

/**
 * Get the IAIK provider.//from   ww  w  .j a  v a  2  s . c o  m
 * @param slot Slot list index or slot ID.
 * @param libFile P11 module so file.
 * @param isIndex true if first parameter is a slot list index, false if slot ID.
 * @return the provider
 */
private static Provider getIAIKP11Provider(final long slot, final File libFile,
        final Pkcs11SlotLabelType type) {
    // Properties for the IAIK PKCS#11 provider
    final Properties prop = new Properties();
    try {
        prop.setProperty("PKCS11_NATIVE_MODULE", libFile.getCanonicalPath());
    } catch (IOException e) {
        throw new RuntimeException("Could for unknown reason not construct canonical filename.", e);
    }
    // If using Slot Index it is denoted by brackets in iaik
    prop.setProperty("SLOT_ID",
            type.equals(Pkcs11SlotLabelType.SLOT_INDEX) ? ("[" + slot + "]") : Long.toString(slot));
    if (log.isDebugEnabled()) {
        log.debug(prop.toString());
    }
    Provider ret = null;
    try {
        @SuppressWarnings("unchecked")
        final Class<? extends Provider> implClass = (Class<? extends Provider>) Class
                .forName(IAIK_PKCS11_CLASS);
        log.info("Using IAIK PKCS11 provider: " + IAIK_PKCS11_CLASS);
        // iaik PKCS11 has Properties as constructor argument
        ret = implClass.getConstructor(Properties.class).newInstance(new Object[] { prop });
        // It's not enough just to add the p11 provider. Depending on algorithms we may have to install the IAIK JCE provider as well in order
        // to support algorithm delegation
        @SuppressWarnings("unchecked")
        final Class<? extends Provider> jceImplClass = (Class<? extends Provider>) Class
                .forName(IAIK_JCEPROVIDER_CLASS);
        Provider iaikProvider = jceImplClass.getConstructor().newInstance();
        if (Security.getProvider(iaikProvider.getName()) == null) {
            log.info("Adding IAIK JCE provider for Delegation: " + IAIK_JCEPROVIDER_CLASS);
            Security.addProvider(iaikProvider);
        }
    } catch (InvocationTargetException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (InstantiationException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (IllegalAccessException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (IllegalArgumentException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (NoSuchMethodException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (SecurityException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (ClassNotFoundException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    }
    return ret;
}

From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

/**
 * Prepare the document for encryption.//  w w  w . java2  s.co m
 *
 * @param doc The document that will be encrypted.
 *
 * @throws CryptographyException If there is an error while encrypting.
 */
public void prepareDocumentForEncryption(PDDocument doc) throws CryptographyException {

    try {
        Security.addProvider(new BouncyCastleProvider());

        PDEncryptionDictionary dictionary = doc.getEncryptionDictionary();
        if (dictionary == null) {
            dictionary = new PDEncryptionDictionary();
        }

        dictionary.setFilter(FILTER);
        dictionary.setLength(this.keyLength);
        dictionary.setVersion(2);

        // remove CF, StmF, and StrF entries that may be left from a previous encryption
        dictionary.removeV45filters();

        dictionary.setSubFilter(SUBFILTER);

        byte[][] recipientsField = new byte[policy.getRecipientsNumber()][];

        // create the 20 bytes seed

        byte[] seed = new byte[20];

        KeyGenerator key = KeyGenerator.getInstance("AES");
        key.init(192, new SecureRandom());
        SecretKey sk = key.generateKey();
        System.arraycopy(sk.getEncoded(), 0, seed, 0, 20); // create the 20 bytes seed

        Iterator it = policy.getRecipientsIterator();
        int i = 0;

        while (it.hasNext()) {
            PublicKeyRecipient recipient = (PublicKeyRecipient) it.next();
            X509Certificate certificate = recipient.getX509();
            int permission = recipient.getPermission().getPermissionBytesForPublicKey();

            byte[] pkcs7input = new byte[24];
            byte one = (byte) (permission);
            byte two = (byte) (permission >>> 8);
            byte three = (byte) (permission >>> 16);
            byte four = (byte) (permission >>> 24);

            System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7 input

            pkcs7input[20] = four;
            pkcs7input[21] = three;
            pkcs7input[22] = two;
            pkcs7input[23] = one;

            DERObject obj = createDERForRecipient(pkcs7input, certificate);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            DEROutputStream k = new DEROutputStream(baos);

            k.writeObject(obj);

            recipientsField[i] = baos.toByteArray();

            i++;
        }

        dictionary.setRecipients(recipientsField);

        int sha1InputLength = seed.length;

        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            sha1InputLength += string.getBytes().length;
        }

        byte[] sha1Input = new byte[sha1InputLength];

        System.arraycopy(seed, 0, sha1Input, 0, 20);

        int sha1InputOffset = 20;

        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            System.arraycopy(string.getBytes(), 0, sha1Input, sha1InputOffset, string.getBytes().length);
            sha1InputOffset += string.getBytes().length;
        }

        MessageDigest md = MessageDigest.getInstance("SHA-1");

        byte[] mdResult = md.digest(sha1Input);

        this.encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8);

        doc.setEncryptionDictionary(dictionary);
        doc.getDocument().setEncryptionDictionary(dictionary.encryptionDictionary);

    } catch (NoSuchAlgorithmException ex) {
        throw new CryptographyException(ex);
    } catch (NoSuchProviderException ex) {
        throw new CryptographyException(ex);
    } catch (Exception e) {
        LOG.error(e, e);
        throw new CryptographyException(e);
    }

}