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:be.fedict.eid.dss.model.bean.IdentityServiceSingletonBean.java

/**
 * Load identity keystore//from w w w  . j a va2 s .  c o  m
 * 
 * @param dssIdentityConfig
 *            identity configuration
 * @return private key entry of identity
 * @throws KeyStoreLoadException
 *             failed to load keystore
 */
public PrivateKeyEntry loadIdentity(DSSIdentityConfig dssIdentityConfig) throws KeyStoreLoadException {

    try {

        if (null == dssIdentityConfig) {
            throw new KeyStoreLoadException("Identity config is empty!");
        }

        FileInputStream keyStoreInputStream = null;
        if (dssIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) {
            Security.addProvider(new SunPKCS11(dssIdentityConfig.getKeyStorePath()));
        } else {
            try {
                keyStoreInputStream = new FileInputStream(dssIdentityConfig.getKeyStorePath());
            } catch (FileNotFoundException e) {
                throw new KeyStoreLoadException("Can't load keystore from config-specified location: "
                        + dssIdentityConfig.getKeyStorePath(), e);
            }
        }

        // load keystore
        KeyStore keyStore = KeyStore.getInstance(dssIdentityConfig.getKeyStoreType().getJavaKeyStoreType());
        char[] password;
        if (null != dssIdentityConfig.getKeyStorePassword()
                && !dssIdentityConfig.getKeyStorePassword().isEmpty()) {
            password = dssIdentityConfig.getKeyStorePassword().toCharArray();
        } else {
            password = null;
        }
        keyStore.load(keyStoreInputStream, password);

        // find entry alias
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new KeyStoreLoadException("no keystore aliases present");
        }

        String alias;
        if (null != dssIdentityConfig.getKeyEntryAlias()
                && !dssIdentityConfig.getKeyEntryAlias().trim().isEmpty()) {
            boolean found = false;
            while (aliases.hasMoreElements()) {
                if (aliases.nextElement().equals(dssIdentityConfig.getKeyEntryAlias())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new KeyStoreLoadException(
                        "no keystore entry with alias \"" + dssIdentityConfig.getKeyEntryAlias() + "\"");
            }
            alias = dssIdentityConfig.getKeyEntryAlias();
        } else {
            alias = aliases.nextElement();
        }
        LOG.debug("keystore alias: " + alias);

        // get keystore entry
        char[] entryPassword;
        if (null != dssIdentityConfig.getKeyEntryPassword()
                && !dssIdentityConfig.getKeyEntryPassword().isEmpty()) {
            entryPassword = dssIdentityConfig.getKeyEntryPassword().toCharArray();
        } else {
            entryPassword = null;
        }

        KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword));
        if (!(entry instanceof PrivateKeyEntry)) {
            throw new KeyStoreLoadException("private key entry expected");
        }
        return (PrivateKeyEntry) entry;
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException(e);
    } catch (CertificateException e) {
        throw new KeyStoreLoadException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreLoadException(e);
    } catch (UnrecoverableEntryException e) {
        throw new KeyStoreLoadException(e);
    } catch (IOException e) {
        throw new KeyStoreLoadException(e);
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

void install(String[] redirectEndpointUrls, String[] postLogoutRedirectUrls, String logoutUrl)
        throws Exception {
    String domainControllerFQDN = this.relyingPartyConfig.getOpFQDN();
    int domainControllerPort = Integer.parseInt(this.relyingPartyConfig.getOpListeningPort());
    String tenant = this.relyingPartyConfig.getTenant();

    // retrieve OIDC meta data
    MetadataHelper metadataHelper = new MetadataHelper.Builder(domainControllerFQDN)
            .domainControllerPort(domainControllerPort).tenant(tenant).keyStore(this.keyStore).build();

    ProviderMetadata providerMetadata = metadataHelper.getProviderMetadata();
    RSAPublicKey providerPublicKey = metadataHelper.getProviderRSAPublicKey(providerMetadata);

    // create a non-registered OIDC client and get bearer tokens by admin user name/password
    ConnectionConfig connectionConfig = new ConnectionConfig(providerMetadata, providerPublicKey,
            this.keyStore);
    ClientConfig clientConfig = new ClientConfig(connectionConfig, null, null);
    OIDCClient nonRegisteredClient = new OIDCClient(clientConfig);
    TokenSpec tokenSpec = new TokenSpec.Builder(TokenType.BEARER)
            .resourceServers(Arrays.asList("rs_admin_server")).build();
    OIDCTokens oidcTokens = nonRegisteredClient.acquireTokensByPassword(
            this.relyingPartyConfig.getAdminUsername(), this.relyingPartyConfig.getAdminPassword(), tokenSpec);

    // create a private/public key pair, generate a certificate and assign it to a solution user name.
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    String solutionUserName = this.relyingPartyConfig.getClientPrefix() + UUID.randomUUID().toString();
    X509Certificate clientCertificate = generateCertificate(keypair, solutionUserName);

    // create REST idm client
    IdmClient idmClient = createIdmClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);/*from   ww  w. j av a  2s. c  o m*/

    VmdirClient vmdirClient = createVMdirClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);

    // create a solution user
    CertificateDTO certificateDTO = new CertificateDTO.Builder()
            .withEncoded(convertToBase64PEMString(clientCertificate)).build();
    SolutionUserDTO solutionUserDTO = new SolutionUserDTO.Builder().withName(solutionUserName)
            .withDomain(tenant).withCertificate(certificateDTO).build();
    vmdirClient.solutionUser().create(tenant, solutionUserDTO);

    // add the solution user to ActAs group
    List<String> members = Arrays.asList(solutionUserName + "@" + tenant);
    vmdirClient.group().addMembers(tenant, "ActAsUsers", tenant, members,
            com.vmware.directory.rest.common.data.MemberType.USER);

    // register a OIDC client
    OIDCClientMetadataDTO oidcClientMetadataDTO = new OIDCClientMetadataDTO.Builder()
            .withRedirectUris(Arrays.asList(redirectEndpointUrls))
            .withPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUrls)).withLogoutUri(logoutUrl)
            .withTokenEndpointAuthMethod("private_key_jwt")
            .withCertSubjectDN(clientCertificate.getSubjectDN().getName())
            .withAuthnRequestClientAssertionLifetimeMS(2 * 60 * 1000L).build();
    OIDCClientDTO oidcClientDTO = idmClient.oidcClient().register(tenant, oidcClientMetadataDTO);

    // persist data involved installation in files so they can be picked up in case server reboots
    savePublicKey(this.relyingPartyConfig.getOpPublickeyFile(), providerPublicKey);
    savePrivateKey(this.relyingPartyConfig.getRpPrivatekeyFile(), keypair.getPrivate());
    writeObject(this.relyingPartyConfig.getRpCertificateFile(), clientCertificate);
    writeObject(this.relyingPartyConfig.getRpInfoFile(), oidcClientDTO.getClientId());
    writeObject(this.relyingPartyConfig.getRpListeningPortFile(), this.relyingPartyConfig.getRpListeningPort());
}

From source file:org.jboss.as.test.integration.security.loginmodules.LdapExtLDAPServerSetupTask.java

/**
 * Creates directory services, starts LDAP server and KDCServer
 *
 * @param managementClient/*from w w  w  .  ja  va 2 s  . c  o m*/
 * @param containerId
 * @throws Exception
 * @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
 * java.lang.String)
 */
public void setup(ManagementClient managementClient, String containerId) throws Exception {
    try {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
            removeBouncyCastle = true;
        }
    } catch (SecurityException ex) {
        LOGGER.warn("Cannot register BouncyCastleProvider", ex);
    }

    final String hostname = Utils.getSecondaryTestAddress(managementClient, false);
    createLdap1(hostname);
    createLdap2(hostname);
}

From source file:org.cryptomator.crypto.aes256.Aes256CryptorTest.java

License:asdf

@Test
public void foo() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());

    final byte[] iv = new byte[16];
    final byte[] keyBytes = new byte[16];
    final SecretKey key = new SecretKeySpec(keyBytes, "AES");
    final Cipher pkcs5PaddedCipher = Cipher.getInstance("AES/CTR/PKCS5Padding",
            BouncyCastleProvider.PROVIDER_NAME);
    pkcs5PaddedCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
    final Cipher unpaddedCipher = Cipher.getInstance("AES/CTR/NoPadding");
    unpaddedCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));

    // test data:
    final byte[] plaintextData = "Hello World".getBytes();
    final byte[] pkcs5PaddedCiphertext = pkcs5PaddedCipher.doFinal(plaintextData);
    final byte[] unpaddedCiphertext = unpaddedCipher.doFinal(plaintextData);

    Assert.assertFalse(Arrays.equals(pkcs5PaddedCiphertext, unpaddedCiphertext));
}

From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java

@SuppressWarnings("resource")
public void run() {

    SingletonForSSFMP info = null;// w w  w  .  j av  a 2s  .  c  o  m
    SingletonForSSFMP2 info2 = null;
    SingletonForSSFMP3 info3 = null;

    switch (abs) {
    case 0:
        info = SingletonForSSFMP.getInstance();
        break;
    case 1:
        info2 = SingletonForSSFMP2.getInstance();
        break;
    case 2:
        info3 = SingletonForSSFMP3.getInstance();
        break;
    default:
        //info = SingletonForMyStreamer.getInstance();
        break;
    }

    int seqTsEnc = 0; //info.getSeqTsEnc();
    if (!modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsEnc();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsEnc();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsEnc();
        }
    } else if (modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsCapturedTimeShifted();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsCapturedTimeShifted();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsCapturedTimeShifted();
        }
    }

    if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
        seqTsEnc = info.getSeqTsLast();
    } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
        seqTsEnc = info2.getSeqTsLast();
    } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
        seqTsEnc = info3.getSeqTsLast();
    }

    log.debug(MARKER_Encrypter, "{} Begin : Encryption of seqTsEnc : {}",
            Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

    Key sKey;
    Cipher c;
    FileOutputStream keyOut;
    FileWriter ivOut;
    FileInputStream fis;
    BufferedInputStream bis;
    FileOutputStream fos;
    CipherOutputStream cos;

    try {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        sKey = makeKey(128); // Key length is 128bit
        c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        //         log.debug(MARKER_Encrypter, "{} [c.getAlgorithm()] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), c.getAlgorithm());
        c.init(Cipher.ENCRYPT_MODE, sKey);

        // Set Key File Name at random
        String keyPre = RandomStringUtils.randomAlphabetic(10);
        keyOut = new FileOutputStream(streamPath + FILE_SEPARATOR + keyPre + seqTsEnc + ".key");

        if ((abs == 0) && (info != null)) {
            info.addKeyArrayList(keyPre);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addKeyArrayList(keyPre);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addKeyArrayList(keyPre);
        }

        byte[] keyOutByte = sKey.getEncoded();
        keyOut.write(keyOutByte);
        keyOut.close();

        byte[] iv = c.getIV();
        //         log.debug(MARKER_Encrypter, "{} [iv.length] {} [byte]", Thread.currentThread().getStackTrace()[1].getMethodName(), iv.length);

        String ivHex = "";
        for (int i = 0; i < iv.length; i++) {
            String ivHexTmp = String.format("%02x", iv[i]).toUpperCase();
            ivHex = ivHex + ivHexTmp;
        }

        String ivPre = RandomStringUtils.randomAlphabetic(10);
        ivOut = new FileWriter(streamPath + FILE_SEPARATOR + ivPre + seqTsEnc + ".iv");
        ivOut.write(ivHex);
        ivOut.close();

        //         log.debug(MARKER_Encrypter, "{} [iv] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), ivHex);

        if ((abs == 0) && (info != null)) {
            info.addIvArrayList(ivHex);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addIvArrayList(ivHex);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addIvArrayList(ivHex);
        }

        fis = new FileInputStream(TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequence" + seqTsEnc + ".ts");
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
        cos = new CipherOutputStream(fos, c);
        if (modeLive.equals("capturedTimeShifted")) {
            fis = new FileInputStream(
                    TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequenceEncoded" + seqTsEnc + ".ts");
            bis = new BufferedInputStream(fis);
            fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
            cos = new CipherOutputStream(fos, c);
        }

        byte[] buf = new byte[TS_PACKET_LENGTH];

        int ch;
        while ((ch = bis.read(buf)) != -1) {
            cos.write(buf, 0, ch);
        }
        cos.close();
        fos.close();
        bis.close();
        fis.close();

        log.debug(MARKER_Encrypter, "{} End : Encryption of seqTsEnc : {}",
                Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

        if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        }

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } // try
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

private static void initialize() {
    (new File(APP_PATH)).mkdir();
    if (OS == OS_WIN)
        Security.addProvider(new BouncyCastleProvider());
    System.out.println("APP_PATH: " + APP_PATH);
    try {/*from   w  w w. j  a v a2s . c  om*/
        sLogFileHandler = new FileHandler(sLog);
    } catch (SecurityException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    } catch (IOException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    }

    File propertiesFile = new File(sProperties);
    if (!propertiesFile.exists()) {
        try {
            propertiesFile.createNewFile();
        } catch (IOException e) {
            writeLog("propertiesFile.createNewFile: " + e.getMessage());
        }
    }

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream(sProperties));
        if (prop.isEmpty()) {
            prop.setProperty(sPassphraseKey, sPassphrase);
            prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
            prop.store(new FileOutputStream(sProperties), null);
        } else {
            if (prop.containsKey(sPassphraseKey))
                sPassphrase = prop.getProperty(sPassphraseKey);
            else
                prop.setProperty(sPassphraseKey, sPassphrase);
            if (prop.containsKey(sDisplaySystemTrayKey))
                sDisplaySystemTray = Boolean.parseBoolean(prop.getProperty(sDisplaySystemTrayKey));
            else
                prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            if (prop.containsKey(sDebuggingKey))
                sDebugging = Boolean.parseBoolean(prop.getProperty(sDebuggingKey));
            else
                prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
        }
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }

    if (sLogFileHandler != null) {
        sLogger = Logger.getLogger("TapLock");
        sLogger.setUseParentHandlers(false);
        sLogger.addHandler(sLogFileHandler);
        SimpleFormatter sf = new SimpleFormatter();
        sLogFileHandler.setFormatter(sf);
        writeLog("service starting");
    }

    if (sDisplaySystemTray && SystemTray.isSupported()) {
        final SystemTray systemTray = SystemTray.getSystemTray();
        Image trayIconImg = Toolkit.getDefaultToolkit()
                .getImage(TapLockServer.class.getResource("/systemtrayicon.png"));
        final TrayIcon trayIcon = new TrayIcon(trayIconImg, "Tap Lock");
        trayIcon.setImageAutoSize(true);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem toggleSystemTrayIcon = new CheckboxMenuItem("Display Icon in System Tray");
        toggleSystemTrayIcon.setState(sDisplaySystemTray);
        CheckboxMenuItem toggleDebugging = new CheckboxMenuItem("Debugging");
        toggleDebugging.setState(sDebugging);
        MenuItem shutdownItem = new MenuItem("Shutdown Tap Lock Server");
        popupMenu.add(aboutItem);
        popupMenu.add(toggleSystemTrayIcon);
        if (OS == OS_WIN) {
            MenuItem setPasswordItem = new MenuItem("Set password");
            popupMenu.add(setPasswordItem);
            setPasswordItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel panel = new JPanel();
                    JLabel label = new JLabel("Enter your Windows account password:");
                    JPasswordField passField = new JPasswordField(32);
                    panel.add(label);
                    panel.add(passField);
                    String[] options = new String[] { "OK", "Cancel" };
                    int option = JOptionPane.showOptionDialog(null, panel, "Tap Lock", JOptionPane.NO_OPTION,
                            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (option == 0) {
                        String password = encryptString(new String(passField.getPassword()));
                        if (password != null) {
                            Properties prop = new Properties();
                            try {
                                prop.load(new FileInputStream(sProperties));
                                prop.setProperty(sPasswordKey, password);
                                prop.store(new FileOutputStream(sProperties), null);
                            } catch (FileNotFoundException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            } catch (IOException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            }
                        }
                    }
                }
            });
        }
        popupMenu.add(toggleDebugging);
        popupMenu.add(shutdownItem);
        trayIcon.setPopupMenu(popupMenu);
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            writeLog("systemTray.add: " + e.getMessage());
        }
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newline = System.getProperty("line.separator");
                newline += newline;
                JOptionPane.showMessageDialog(null, "Tap Lock" + newline + "Copyright (c) 2012 Bryan Emmanuel"
                        + newline
                        + "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."
                        + newline
                        + "This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details."
                        + newline
                        + "You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>."
                        + newline + "Bryan Emmanuel piusvelte@gmail.com");
            }
        });
        toggleSystemTrayIcon.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setTrayIconDisplay(e.getStateChange() == ItemEvent.SELECTED);
                if (!sDisplaySystemTray)
                    systemTray.remove(trayIcon);
            }
        });
        toggleDebugging.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setDebugging(e.getStateChange() == ItemEvent.SELECTED);
            }
        });
        shutdownItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    synchronized (sConnectionThreadLock) {
        (sConnectionThread = new ConnectionThread()).start();
    }
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String reason, String location, String contact)
        throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path signedPDF = Files.createTempFile("signed", ".pdf");

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    IOUtils.closeQuietly(is);/*from   w w  w  .j  ava 2  s. c o m*/

    PdfReader reader = new PdfReader(input.toString());
    FileOutputStream os = new FileOutputStream(signedPDF.toFile());
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    appearance.setContact(contact);
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature");
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
    MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null);
    IOUtils.closeQuietly(os);
    reader.close();

    return signedPDF;
}

From source file:com.oneops.cms.crypto.CmsCryptoDES.java

/**
 * Inits the./* w  w  w  .  j a  v  a2s . c  om*/
 *
 * @throws java.io.IOException              Signals that an I/O exception has occurred.
 * @throws java.security.GeneralSecurityException the general security exception
 */
public void init() throws IOException, GeneralSecurityException {
    Security.addProvider(new BouncyCastleProvider());
    this.secretKeyFile = System.getenv("CMS_DES_PEM");
    if (this.secretKeyFile == null) {
        this.secretKeyFile = System.getProperty("com.kloopz.crypto.cms_des_pem");
    }

    if (this.secretKeyFile == null) {
        logger.error(
                ">>>>>>>>>>>>>>Failed to init DES Encryptor/Decryptor no key faile is set, use CMS_DES_PEM env var to set location!");
        throw new FileNotFoundException(
                "Failed to init DES Encryptor/Decryptor no key faile is set, use CMS_DES_PEM env var to set location!");
    }
    initEncryptorDecryptor();
}

From source file:org.lsc.utils.security.SymmetricEncryption.java

/**
 * New SymmetricEncryption object.//from  w w  w  .  j a  v  a 2  s.  c  om
 * @param encryption the encryption required structure
 * @throws java.security.GeneralSecurityException
 */
public SymmetricEncryption(EncryptionType encryption) throws GeneralSecurityException {
    if (encryption == null) {
        throw new RuntimeException("lsc>security>encryption node of the LSC configuration cannot be null !");
    } else if (encryption.getKeyfile() == null) {
        throw new RuntimeException(
                "lsc>security>encryption>keyfile node of the LSC configuration cannot be null !");
    } else if (encryption.getAlgorithm() == null) {
        throw new RuntimeException(
                "lsc>security>encryption>algorithm node of the LSC configuration cannot be null !");
    }

    this.securityProvider = new BouncyCastleProvider();
    this.algorithm = encryption.getAlgorithm();
    this.strength = encryption.getStrength();
    this.keyPath = encryption.getKeyfile();

    Security.addProvider(this.securityProvider);
}

From source file:com.infinities.keystone4j.utils.Cms.java

private String cmsSignData(String data, String signingCertFileName, String signingKeyFile, String outform)
        throws CertificateException, IOException, NoSuchAlgorithmException, NoSuchProviderException,
        CMSException, OperatorCreationException, CertStoreException {
    if (Strings.isNullOrEmpty(outform)) {
        outform = PKI_ASN1_FORM;/*w  ww. j a  v  a2  s  .  c o m*/
    }

    Security.addProvider(new BouncyCastleProvider());
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, signingKeyFile });
    X509Certificate signercert = generateCertificate(signingCertFileName);
    // X509Certificate cacert = generateCertificate(caFileName);
    PrivateKey key = generatePrivateKey(signingKeyFile);
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(key);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, signercert));
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(signercert);
    Store certs = new JcaCertStore(certList);
    gen.addCertificates(certs);

    CMSProcessableByteArray b = new CMSProcessableByteArray(data.getBytes());
    CMSSignedData signed = gen.generate(b, true);
    String signedContent = new String(DERtoPEM(signed.getContentInfo().getDEREncoded(), "CMS"));
    return signedContent;
}