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:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testGetCertificateCaching() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from  w ww  .  ja v a 2s  .  c o m

    for (int idx = 0; idx < 100; idx++) {
        assertNotNull(keyStore.getCertificate("Authentication"));
    }
}

From source file:org.wso2.identity.integration.test.user.store.config.UserStorePasswordEncryption.java

private byte[] decrypt(byte[] cipherTextBytes, String cipherTransformation) throws CryptoException {
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    try {/*from  w  w w .ja v a  2  s.  c o  m*/
        Security.addProvider(bouncyCastleProvider);
        Cipher keyStoreCipher;
        PrivateKey privateKey = (PrivateKey) getKeyStore(keyStoreFilePath, "wso2carbon", "wso2carbon")
                .getKey("wso2carbon", "wso2carbon".toCharArray());
        keyStoreCipher = Cipher.getInstance(cipherTransformation, "BC");
        keyStoreCipher.init(Cipher.DECRYPT_MODE, privateKey);
        return keyStoreCipher.doFinal(cipherTextBytes);
    } catch (Exception e) {
        throw new CryptoException("Error occurred while decryption", e);
    } finally {
        Security.removeProvider(bouncyCastleProvider.getName());
    }
}

From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 *
 * @param issuerCert   is the Certificate of the Issuer of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request.// ww  w.ja  va  2  s. com
 * @throws CertificateVerificationException
 *
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateVerificationException {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {

        byte[] issuerCertEnc = issuerCert.getEncoded();
        X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();

        //  CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
        CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder,
                serialNumber);

        // basic request generation with nonce
        OCSPReqBuilder builder = new OCSPReqBuilder();
        builder.addRequest(id);

        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent replay attacks. As the name implies,
        // the nonce value is something that the client should only use once within a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());

        //to create the request Extension
        builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce,
                false, new DEROctetString(nonce.toByteArray()))));

        return builder.build();

    } catch (Exception e) {
        throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate",
                e);
    }
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

/**
 * Default constructor.//from   www.  ja va2  s  .  c  o  m
 */
DigitalSigningHelper() {

    if (Security.getProvider(BOUNCY_CASTLE_PROVIDER) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }

}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

public boolean checkSignature(byte[] Document) {
    try {/*from  w  w  w.ja v  a2s  . co  m*/
        System.out.println("Beginning of Checking XmlSignature:");
        System.out.println(Document);

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

        // extract the Signed Fingerprint data
        CMSSignedData signature = new CMSSignedData(Document);
        System.out.println("Beginning of Checking XmlSignature:");

        SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator()
                .next();
        System.out.println("Beginning of Checking XmlSignature:");

        // Get from the collection the appropriate registered certificate
        CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");
        Iterator iter = cs.getCertificates(signer.getSID()).iterator();
        System.out.println("Beginning of Checking XmlSignature:");
        X509Certificate certificate = (X509Certificate) iter.next();
        System.out.println("Beginning of Checking XmlSignature:");
        // get the contents of the document
        CMSProcessable sg = signature.getSignedContent();
        byte[] data = (byte[]) sg.getContent();
        String content = new String(data);

        //convert the document content to a valid xml document for YAWL
        org.w3c.dom.Document XMLNode = ConvertStringToDocument(content);
        org.jdom2.input.DOMBuilder builder = new org.jdom2.input.DOMBuilder();
        Doc = builder.build(XMLNode);

        //Check the document
        System.out.println("xml to Sign:");
        System.out.println(JDOMUtil.documentToString(Doc));

        // get the name of the signer
        _Name = certificate.getSubjectDN().getName().split("(=|, )", -1).toString();
        //return the result of the signature checking
        return signer.verify(certificate, "BC");

    } catch (Exception e) {
        System.out.println("Test error");
        e.printStackTrace();
        return false;
    }

}

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java

@Test
public void testPublishAnnex() throws Exception {
    // STS// w w w  .  ja v  a2 s .c o m
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox publication
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] message = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(message);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(message);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    List<PublicationAnnexType> publicationAnnexList = publicationContent.getAnnex();
    PublicationAnnexType publicationAnnex = objectFactory.createPublicationAnnexType();
    publicationAnnexList.add(publicationAnnex);
    publicationAnnex.setDownloadFileName("test.txt");
    publicationAnnex.setEncryptableTitle("hello world".getBytes());
    publicationAnnex.setMimeType("application/octet-stream");
    publicationAnnex.setEncryptableTextContent(message);
    messageDigest.reset();
    digest = messageDigest.digest(message);
    publicationAnnex.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();

    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

@Restrict("#{s:hasPermission('configuration', 'access')}")
public String generateCSR(String fileName) {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//from  ww w.  j  ava2 s  .  c o  m

    KeyPair pair = getKeyPair(fileName);
    boolean result = false;
    if (pair != null) {
        String url = applicationConfiguration.getIdpUrl().replaceFirst(".*//", "");
        String csrPrincipal = String.format("CN=%s", url);
        X500Principal principal = new X500Principal(csrPrincipal);

        PKCS10CertificationRequest csr = null;
        try {
            csr = new PKCS10CertificationRequest("SHA1withRSA", principal, pair.getPublic(), null,
                    pair.getPrivate());
        } catch (GeneralSecurityException e) {
            log.error(e.getMessage(), e);
            return OxTrustConstants.RESULT_FAILURE;
        }

        // Form download responce
        StringBuilder response = new StringBuilder();

        response.append(BEGIN_CERT_REQ + "\n");
        response.append(WordUtils.wrap(new String(Base64.encode(csr.getDEREncoded())), 64, "\n", true) + "\n");
        response.append(END_CERT_REQ + "\n");

        result = ResponseHelper.downloadFile("csr.pem", OxTrustConstants.CONTENT_TYPE_TEXT_PLAIN,
                response.toString().getBytes(), facesContext);
    }

    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

/**
 * Signs the PDF using the given token.//from www  .j  av  a 2 s.  c o m
 * 
 * @param bytes the PDF to sign
 * @param token the token to sign with
 * @return the sealed PDF
 */
public static byte[] signPdf(final byte[] bytes, final SignatureTokenConnection token) {
    InputStream is = null;
    try {
        Security.addProvider(new BouncyCastleProvider());
        CommonCertificateVerifier certificateVerifier = new CommonCertificateVerifier();
        final PAdESService service = new PAdESService(certificateVerifier) {
            @Override
            protected void assertSigningDateInCertificateValidityRange(
                    eu.europa.ec.markt.dss.parameter.SignatureParameters parameters) {
                // we don't care about the date because it's not a real signature
            }
        };
        final DSSPrivateKeyEntry key = token.getKeys().get(0);
        final DigestAlgorithm digestAlgorithm = DigestAlgorithm.SHA512;

        final SignatureParameters parameters = new SignatureParameters();
        parameters.setSigningCertificate(key.getCertificate());
        if (key.getCertificateChain() != null) {

            List<X509Certificate> chain = new ArrayList<X509Certificate>();
            for (X509Certificate c : key.getCertificateChain()) {
                chain.add(c);
            }
            X509Certificate[] chainArray = new X509Certificate[chain.size()];
            chainArray = chain.toArray(chainArray);
            parameters.setCertificateChain(chainArray);
        }
        parameters.setSignatureLevel(SignatureLevel.PAdES_BASELINE_B);
        parameters.setSignaturePackaging(SignaturePackaging.ENVELOPED);
        parameters.bLevel().setSigningDate(new Date());
        parameters.setDigestAlgorithm(digestAlgorithm);
        parameters.setSigningToken(token);
        parameters.setPrivateKeyEntry(key);
        final DSSDocument document = new InMemoryDocument(bytes);
        final DSSDocument doc = service.signDocument(document, parameters);
        is = doc.openStream();
        return IOUtils.toByteArray(is);
    } catch (IOException e) {
        throw new SigningException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }

}

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

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

    // operate
    X509Certificate citizenCACertificate = (X509Certificate) keyStore.getCertificate("CA");
    X509Certificate rootCACertificate = (X509Certificate) keyStore.getCertificate("Root");
    X509Certificate rrnCertificate = (X509Certificate) keyStore.getCertificate("RRN");

    // verify
    assertNotNull(citizenCACertificate);
    LOG.debug("citizen CA: " + citizenCACertificate.getSubjectX500Principal());
    assertNotNull(rootCACertificate);
    LOG.debug("root CA: " + rootCACertificate.getSubjectX500Principal());
    assertNotNull(rrnCertificate);
    assertTrue(rrnCertificate.getSubjectX500Principal().toString().contains("RRN"));
}

From source file:sernet.gs.ui.rcp.main.security.VeriniceSecurityProvider.java

private void setupSunPKCS11Provider() {
    // Prevents installing the provider twice.
    if (Security.getProvider("SunPKCS11-verinice") != null) {
        return;// w ww. ja v  a  2 s  . c o  m
    }
    // If the user enabled anything PKCS#11 related we need to lead the PKCS#11 library and add its
    // provider.
    String configFile = createPKCS11ConfigFile();
    if (configFile != null) {
        // The availability of this class in an OSGi environment depends on a system property. If
        // get errors of this class not being available check that you have
        // -Dosgi.parentClassloader=ext
        // in your VM arguments.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Setup SunPKCS11 AuthProvider with config file: " + configFile);
        }
        SunPKCS11 p = new SunPKCS11(configFile);
        p.setCallbackHandler(new Helper() {
            @Override
            protected void handle(PasswordCallback cb) {
                cb.setPassword(getTokenPIN());
            }
        });
        Security.addProvider(p);
    }
}