Example usage for java.security KeyStore getCertificateChain

List of usage examples for java.security KeyStore getCertificateChain

Introduction

In this page you can find the example usage for java.security KeyStore getCertificateChain.

Prototype

public final Certificate[] getCertificateChain(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate chain associated with the given alias.

Usage

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste de coassinatura com envio do hash calculado
 *//*w  ww. j  ava2  s .c  om*/
//@Test
public void testCoSignHash() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo
        String fileDirName = "local_e_nome_do_arquivo_para_assinar";
        String fileSignatureDirName = "local_e_nome_do_arquivo_da_assinatura";

        byte[] fileToSign = readContent(fileDirName);
        byte[] signatureFile = readContent(fileSignatureDirName);

        // gera o hash do arquivo
        java.security.MessageDigest md = java.security.MessageDigest
                .getInstance(DigestAlgorithmEnum.SHA_512.getAlgorithm());
        // devido a uma restrio do token branco, no windws s funciona com 256
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            md = java.security.MessageDigest.getInstance(DigestAlgorithmEnum.SHA_256.getAlgorithm());
        }

        byte[] hash = md.digest(fileToSign);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Token
        KeyStore ks = getKeyStoreToken();

        // Para certificado em arquivo A1
        // KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);

        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // seta o algoritmo de acordo com o que foi gerado o Hash
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada
        byte[] signature = signer.doHashCoSign(hash, signatureFile);
        File file = new File(fileDirName + "hash-co.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste com envio do contedo/*from   w  w w .ja  v a2 s .c  o m*/
 */
//@Test
public void testSignDetached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo

        //
        //String fileDirName = "C:\\Users\\{usuario}\\arquivo_assinar";
        String fileDirName = "";

        byte[] fileToSign = readContent(fileDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // MSCAPI off
        //org.demoiselle.signer.core.keystore.loader.configuration.Configuration.setMSCAPI_ON(false);

        // Setar Proxy
        // Proxy.setProxyEndereco("localhost");
        //Proxy.setProxyPorta("3128");
        //Proxy.setProxySenha("senha");
        //Proxy.setProxyUsuario("usuario");
        //Proxy.setProxy();

        // Para certificado NeoID e windows token
        //KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em arquivo A1
        KeyStore ks = getKeyStoreFileBySigner();
        // Para certificado token Linux
        //KeyStore ks = getKeyStoreToken();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);
        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        //signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica referencia bsica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // referencia de validao
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RV_CADES_2_3);
        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada

        // Cache de cadeia
        //CAManagerConfiguration config = CAManagerConfiguration.getInstance();
        //config.setCached(true);
        //org.demoiselle.signer.core.ca.manager.CAManagerConfiguration.getInstance().setCached(true);

        // Cache LCR
        //Configuration config = Configuration.getInstance();
        //config.setCrlIndex(".crl_index");
        //config.setCrlPath("/home/{usuario}/lcr_cache/");
        //config.setOnline(false);

        // Diretorio LPA
        //Configuration config = Configuration.getInstance();
        //config.setLpaPath("/home/{usuario}/.signer");

        byte[] signature = signer.doDetachedSign(fileToSign);
        File file = new File(fileDirName + "_detached_rb.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        assertTrue(true);

    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testRRNCertificate() throws Exception {
    // setup/*from  w w w . ja v a  2  s  .  c  o  m*/
    Security.addProvider(new BeIDProvider());
    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    // operate
    assertTrue(keyStore.containsAlias("RRN"));
    Entry entry = keyStore.getEntry("RRN", null);
    assertNotNull(entry);
    assertTrue(entry instanceof TrustedCertificateEntry);
    TrustedCertificateEntry trustedCertificateEntry = (TrustedCertificateEntry) entry;
    assertNotNull(trustedCertificateEntry.getTrustedCertificate());
    assertTrue(((X509Certificate) trustedCertificateEntry.getTrustedCertificate()).getSubjectX500Principal()
            .toString().contains("RRN"));
    assertNotNull(keyStore.getCertificate("RRN"));
    Certificate[] certificateChain = keyStore.getCertificateChain("RRN");
    assertNotNull(certificateChain);
    assertEquals(2, certificateChain.length);
    LOG.debug("RRN subject: " + ((X509Certificate) certificateChain[0]).getSubjectX500Principal());
    LOG.debug("RRN issuer: " + ((X509Certificate) certificateChain[0]).getIssuerX500Principal());
    LOG.debug("root subject: " + ((X509Certificate) certificateChain[1]).getSubjectX500Principal());
    LOG.debug("root issuer: " + ((X509Certificate) certificateChain[1]).getIssuerX500Principal());
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public String generateNodePKCS7CertificateChainString() throws CertificateException {
    KeyStore keyStore = loadKeyStore();
    Key key;//from w w w. j  a  v  a 2s  .  c  om
    try {
        key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray());
    } catch (UnrecoverableKeyException e) {
        throw new CertificateException("Error opening node private key", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node private key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error opening node private key", e);
    }
    assert key instanceof PrivateKey;
    Certificate[] chain;
    try {
        chain = keyStore.getCertificateChain(nodeAlias);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error opening node certificate", e);
    }
    X509Certificate[] x509Chain = new X509Certificate[chain.length];
    for (int i = 0; i < chain.length; i++) {
        assert chain[i] instanceof X509Certificate;
        x509Chain[i] = (X509Certificate) chain[i];
    }
    return certificateService.generatePKCS7CertificateChainString(x509Chain);
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste de coassinatura desanexada com envio do contedo
 *//*ww  w  .  j av a 2 s.  c  o  m*/
//@Test
public void testSignCoDetached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo
        String fileDirName = "caminha do arquivo do conteudo";
        String fileSignatureDirName = "caminho do arquivo com a(s) assinatura(s) .p7s";

        byte[] fileToSign = readContent(fileDirName);
        byte[] signatureFile = readContent(fileSignatureDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Neo Id e windows
        KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em Token
        // KeyStore ks = getKeyStoreToken();

        // Para certificado em arquivo A1
        // KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);

        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada
        byte[] signature = signer.doDetachedSign(fileToSign, signatureFile);
        File file = new File(fileDirName + "-co_detached.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        System.out.println("------------------ ok --------------------------");
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste com envio do contedo/*from   w  ww  . j  a v a2s  . c o m*/
 */
//@Test
public void testSignAttached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO ATACHADO*****************");

        // INFORMAR o arquivo
        String fileDirName = "/home/arquivo.txt";

        byte[] fileToSign = readContent(fileDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Token
        KeyStore ks = getKeyStoreToken();

        // Para certificado NeoID e windows token
        //KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em arquivo A1
        //KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);
        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // Referencia de validao
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RA_CADES_2_4);

        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Com conteudo atachado
        byte[] signature = signer.doAttachedSign(fileToSign);
        File file = new File(fileDirName + "_atached.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.PDFSignatureActionExecuter.java

/**
 * /*ww w. java2  s  .c o  m*/
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 * @throws Exception 
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) throws Exception {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE);
    String signedName = (String) ruleAction.getParameterValue(PARAM_SIGNED_NAME);
    int height = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_WIDTH));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    // Ugly and verbose, but fault-tolerant
    String locationXStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_X);
    String locationYStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_Y);
    int locationX = 0;
    int locationY = 0;
    try {
        locationX = locationXStr != null ? Integer.parseInt(locationXStr) : 0;
    } catch (NumberFormatException e) {
        locationX = 0;
    }
    try {
        locationY = locationXStr != null ? Integer.parseInt(locationYStr) : 0;
    } catch (NumberFormatException e) {
        locationY = 0;
    }

    File tempDir = null;
    ContentWriter writer = null;
    KeyStore ks = null;

    try {
        // get a keystore instance by
        if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
        } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) {
            ks = KeyStore.getInstance("pkcs12");
        } else {
            throw new Exception("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = serviceRegistry.getContentService().getReader(privateKey,
                ContentModel.PROP_CONTENT);
        ks.load(keyReader.getContentInputStream(), storePassword.toCharArray());

        // set alias
        //         String alias = (String) ks.aliases().nextElement();

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        //open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        FileOutputStream fout = new FileOutputStream(file);
        PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

        // set reason for signature and location of signer
        sap.setReason(reason);
        sap.setLocation(location);

        if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) {
            sap.setVisibleSignature(new Rectangle(locationX + width, locationY - height, locationX, locationY),
                    1, null);
        }

        stamp.close();

        String[] splitedFilename = file.getName().split("\\.");
        String name = "-" + signedName + "." + splitedFilename[splitedFilename.length - 1];
        for (int i = splitedFilename.length - 2; i >= 0; i--) {
            if (name.equals("-" + signedName + "." + splitedFilename[splitedFilename.length - 1])) {
                name = splitedFilename[i] + name;
            } else {
                name = splitedFilename[i] + "." + name;
            }
        }

        writer = getWriter(name, (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER));
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();
    } catch (Exception e) {
        throw e;
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java

/**
 * //from w w w  . j  av a 2  s.  co  m
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE);
    int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH));
    int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X));
    int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y));

    File tempDir = null;
    ContentWriter writer = null;
    KeyStore ks = null;

    try {
        // get a keystore instance by
        if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
        } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) {
            ks = KeyStore.getInstance("pkcs12");
        } else {
            throw new AlfrescoRuntimeException("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = getReader(privateKey);
        ks.load(keyReader.getContentInputStream(), storePassword.toCharArray());

        // set alias
        // String alias = (String) ks.aliases().nextElement();

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        FileOutputStream fout = new FileOutputStream(file);
        PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

        // set reason for signature and location of signer
        sap.setReason(reason);
        sap.setLocation(location);

        if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) {
            //create the signature rectangle using either the provided position or
            //the exact coordinates, if provided
            if (position != null && !position.trim().equalsIgnoreCase("")) {
                Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber);
                sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null);
            } else {
                sap.setVisibleSignature(
                        new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber,
                        null);
            }
        }

        stamp.close();

        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);

        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();

        //if useAspect is true, store some additional info about the signature in the props
        if (useAspect) {
            serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED,
                    new HashMap<QName, Serializable>());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION,
                    location);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE,
                    new java.util.Date());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY,
                    AuthenticationUtil.getRunAsUser());
        }

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.ejbca.ui.cli.CMPKeyUpdateStressTest.java

@Override
protected void execute(String[] args) {
    final String hostName;
    final String keystoreFile;
    final String keystorePassword;
    final String certNameInKeystore;
    final int numberOfThreads;
    final int waitTime;
    final int port;
    final String urlPath;
    final String resultFilePrefix;
    if (args.length < 5) {
        System.out.println(args[0]
                + " <host name> <keystore (p12)> <keystore password> <friendlyname in keystore> [<number of threads>] [<wait time (ms) between each thread is started>] [<port>] [<URL path of servlet. use 'null' to get EJBCA (not proxy) default>] [<certificate file prefix. set this if you want all received certificates stored on files>]");
        System.out.println(//from  w w w  .j  av  a  2 s .  c o  m
                "EJBCA build configuration requirements: cmp.operationmode=normal, cmp.allowraverifypopo=true, cmp.allowautomatickeyupdate=true, cmp.allowupdatewithsamekey=true");
        //            System.out.println("EJBCA build configuration optional: cmp.ra.certificateprofile=KeyId cmp.ra.endentityprofile=KeyId (used when the KeyId argument should be used as profile name).");
        System.out.println(
                "Ejbca expects the following: There exists an end entity with a generated certificate. The end entity's certificate and its private key are stored in the keystore used "
                        + "in the commandline. The end entity's certificate's 'friendly name' in the keystore is the one used in the command line. Such keystore can be obtained, for example, by specifying "
                        + "the token to be 'P12' when creating the end entity and then download the keystore by choosing 'create keystore' from the public web");
        return;
    }
    hostName = args[1];
    keystoreFile = args[2];
    keystorePassword = args[3];
    certNameInKeystore = args[4];
    numberOfThreads = args.length > 5 ? Integer.parseInt(args[5].trim()) : 1;
    waitTime = args.length > 6 ? Integer.parseInt(args[6].trim()) : 0;
    port = args.length > 7 ? Integer.parseInt(args[7].trim()) : 8080;
    //        isHttp = true;
    urlPath = args.length > 8 && args[8].toLowerCase().indexOf("null") < 0 ? args[8].trim() : null;
    resultFilePrefix = args.length > 9 ? args[9].trim() : null;

    CryptoProviderTools.installBCProviderIfNotAvailable();

    Certificate cacert = null;
    Certificate extracert = null;
    PrivateKey oldCertKey = null;

    FileInputStream file_inputstream;
    try {
        file_inputstream = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, keystorePassword.toCharArray());
        Key key = keyStore.getKey(certNameInKeystore, keystorePassword.toCharArray());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        oldCertKey = keyFactory.generatePrivate(keySpec);
        //extracert = keyStore.getCertificate(certNameInKeystore);

        Certificate[] certs = keyStore.getCertificateChain(certNameInKeystore);
        extracert = certs[0];
        cacert = certs[1];

    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
        System.exit(-1);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        new StressTest(hostName, port, numberOfThreads, waitTime, urlPath, resultFilePrefix, keystorePassword,
                cacert, oldCertKey, extracert);
    } catch (Exception e) {
        e.printStackTrace();
    }
}