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.e_contract.mycarenet.cxf.SyncClientTest.java

@Test
public void testEchoViaInvoke() throws Exception {
    // setup/*from ww  w . j  av  a 2 s.c  om*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    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");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        SyncClient syncClient = new SyncClient("https://pilot.mycarenet.be/services/care-provider/sync",
                sessionKey, packageLicenseKey);

        String result = syncClient
                .invoke("<EchoRequest xmlns=\"urn:be:cin:mycarenet:1.0:sync:types\" xml:lang=\"en\">"
                        + "<test/>" + "</EchoRequest>");

        // verify
        LOG.debug("result: " + result);
    } finally {
        // operate
        xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:com.vmware.demo.SamlService.java

private void init() {
    // Bootstrap the OpenSAML libraries
    if (bootstrap == false) {
        try {// w w w  .  j a  v a2  s .com
            DefaultBootstrap.bootstrap();
            bootstrap = true;
        } catch (ConfigurationException e) {
            logger.error("Failed to bootstrap OpenSAML", e);
        }

        // Add Bouncy Castle provider for x509 parsing
        Security.addProvider(new BouncyCastleProvider());
    }

}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * @throws java.lang.Exception//  w w  w  .ja va2s  .co  m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // Just in case, add the BouncyCastle provider
    // It gets added from the CredentialManagerImpl constructor as well
    // but we may need some crypto operations before we invoke the Cred. Manager 
    Security.addProvider(new BouncyCastleProvider());

    // Create a test username and password for a service
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {

        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub

        }
    };
}

From source file:edu.stanford.muse.email.ImapPopEmailStore.java

public ImapPopEmailStore(ImapPopConnectionOptions options, String emailAddress) {
    super(options.userName + "@" + options.server, emailAddress);
    this.connectOptions = options;
    this.displayName = computeSimpleDisplayName();
    Security.addProvider(new OAuth2Provider());
}

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

/**
 * New SymmetricEncryption object with default values.
 * @throws java.security.GeneralSecurityException
 *///  w ww. j  a  v  a  2  s .co  m
public SymmetricEncryption() throws GeneralSecurityException {
    this.securityProvider = new BouncyCastleProvider();
    Security.addProvider(this.securityProvider);
}

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

public void testJson() throws IOException, Exception {
    Security.addProvider(new BouncyCastleProvider());

    PKBarcode barcode = new PKBarcode();
    barcode.setFormat(PKBarcodeFormat.PKBarcodeFormatQR);
    barcode.setMessage("abcdefg");
    barcode.setMessageEncoding(Charset.forName("UTF-8"));

    PKPass pass = new PKPass();
    pass.setBarcode(barcode);/* ww  w  . j av  a2s .  c om*/
    pass.setPassTypeIdentifier("pti");
    pass.setTeamIdentifier("ti");

    PKSigningInformation pkSigningInformation = PKSigningUtil
            .loadSigningInformationFromPKCS12FileAndIntermediateCertificateFile(keyStorePath, keyStorePassword,
                    appleWWDRCA);
    byte[] signedAndZippedPkPassArchive = PKSigningUtil.createSignedAndZippedPkPassArchive(pass,
            "/Users/patrice/Downloads/passbook/Passes/bitzecheCoupons.raw", pkSigningInformation);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(signedAndZippedPkPassArchive);
    IOUtils.copy(inputStream, new FileOutputStream("/Users/patrice/Downloads/pass.zip"));
}

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

@Test
public void testMutualSSL() throws Exception {

    Security.addProvider(new BeIDProvider());

    final KeyPair serverKeyPair = generateKeyPair();
    final PrivateKey serverPrivateKey = serverKeyPair.getPrivate();
    final DateTime notBefore = new DateTime();
    final DateTime notAfter = notBefore.plusDays(1);
    final X509Certificate serverCertificate = generateCACertificate(serverKeyPair, "CN=Test", notBefore,
            notAfter);/*w ww. j a v  a2 s.c o  m*/

    final KeyManager keyManager = new ServerTestX509KeyManager(serverPrivateKey, serverCertificate);
    final TrustManager trustManager = new ServerTestX509TrustManager();
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { keyManager }, new TrustManager[] { trustManager }, new SecureRandom());

    final SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();

    final int serverPort = 8443;
    final SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory
            .createServerSocket(serverPort);

    sslServerSocket.setNeedClientAuth(true);

    final TestRunnable testRunnable = new TestRunnable(serverPort);
    final Thread thread = new Thread(testRunnable);
    thread.start();

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    LOG.debug("server accepted");
    InputStream inputStream = sslSocket.getInputStream();
    int result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(12, result);
    SSLSession sslSession = sslSocket.getSession();
    sslSession.invalidate();
    sslSocket = (SSLSocket) sslServerSocket.accept();
    inputStream = sslSocket.getInputStream();
    result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(34, result);
}

From source file:org.apache.camel.converter.crypto.PGPDataFormat.java

public PGPDataFormat() {
    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
}

From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java

@Test
public void test() throws Exception {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//  w  w w . ja v a 2  s.c o m

    SignNOApplet applet = new SignNOApplet();
    try {

        // Main options
        boolean applyMark = true;
        boolean useFakeSmartCard = true;
        String driver;
        String scPin;
        if (useFakeSmartCard) {
            driver = "fake";
            scPin = "123";
        } else {
            driver = "libbit4ipki.so";
            scPin = "18071971";
        }

        // Test products
        String[] aliases;
        String alias;
        X509Certificate certificate;
        X509Certificate[] certificateChain;
        byte[] fingerPrint;
        byte[] digitalSignature;

        // Communication unities
        DocumentDTO[] documents;
        String jsonResp;
        SkdsDocumentDetailsResponse detailsResp;
        SkdsPreSignResponse preSignResp;
        SkdsPostSignResponse postSignResp;
        AppletResponseDTO appletResponse;
        SignatureDTO emptySignatureDTO;
        SignatureDTO chainSignatureDTO;
        SignatureDTO digestSignatureDTO;
        SignatureDTO signedSignatureDTO;
        SignatureDTO finalizedSignatureDTO;
        VerifyDTO verifyDTO;

        // Init the applet
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            appletResponse = applet.selectDriver(req);
        } catch (Exception e) {
            tracer.error("error during the applet initialization", e);
            throw e;
        }

        // Login with the smartCard
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            appletResponse = applet.login(req);
            aliases = (String[]) JSONUtils.deserializeJSON(String[].class, extractJSON(appletResponse));
        } catch (Exception e) {
            tracer.error("error during the applet login", e);
            throw e;
        }

        // Choose the signing alias
        StringBuilder buf = new StringBuilder();
        for (String a : aliases) {
            buf.append(a).append(" ");
        }
        alias = aliases[0];
        tracer.info(String.format("available aliases:   %s", buf));
        tracer.info(String.format("signing alias:       %s", alias));

        // Load the certificate chain from the applet
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            req.setAlias(alias);
            appletResponse = applet.selectCertificate(req);
            certificate = (X509Certificate) X509Utils.rawX509CertificateFromHex(extractJSON(appletResponse));
            tracer.info(String.format("certificate:         %s", certificate));
            certificateChain = new X509Certificate[] { certificate };
        } catch (Exception e) {
            tracer.error("error during the certificate selection", e);
            throw e;
        }

        // FindRefByName
        String sourceRef = null;
        try {
            SkdsFindRefByNameRequest req = new SkdsFindRefByNameRequest();
            req.setName(SOURCE_NAME);
            SkdsFindRefByNameResponse findResp = postJsonRequest(req, SkdsFindRefByNameResponse.class);
            if (ResultCode.valueOf(findResp.getResultCode()) == ResultCode.SUCCESS) {
                sourceRef = findResp.getNodeRef();
            } else {
                throw new Exception(findResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // DocumentDetails
        try {
            //            String sourceRef = getNodeRefId("pippo.txt");
            SkdsDocumentDetailsRequest req = new SkdsDocumentDetailsRequest();
            req.setNodeRefs(new String[] { sourceRef });
            //            req.setNodeRefs ( new String[] {SOURCE_REF} );
            detailsResp = postJsonRequest(req, SkdsDocumentDetailsResponse.class);
            if (ResultCode.valueOf(detailsResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = detailsResp.documentsFromBase64();
            } else {
                throw new Exception(detailsResp.getMessage());
            }
            String fileName = documents[0].getBaseDocument().getFileName();
            if (applyMark) {
                documents[0].setDestName(fileName + ".p7m.tsd");
            } else {
                documents[0].setDestName(fileName + ".p7m");
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // empty signature - initialized with the SHA256withRSA and RSA algorithms
        emptySignatureDTO = new SignatureDTO();
        emptySignatureDTO.setSignAlgorithm(conf.getSignatureAlgorithm().getName());
        emptySignatureDTO.setDigestAlgorithm(conf.getDigestAlgorithm().getName());
        emptySignatureDTO.signCategoryToString(SignCategory.CMS);

        // Add to the empty signature the timeStamp request if needed
        TimeStampRequestDTO tsRequestDTO = new TimeStampRequestDTO();
        if (applyMark) {
            tsRequestDTO.timestampDispositionToString(SignDisposition.TimeStamp.ENVELOPING);
            tsRequestDTO.messageImprintAlgorithmToString(DigestAlgorithm.SHA256);
            tsRequestDTO.nounceToString(BigInteger.TEN);
            tsRequestDTO.setTsUrl("http://ca.signfiles.com/TSAServer.aspx");
        }
        emptySignatureDTO.setTimeStampRequest(tsRequestDTO);

        // chain signature - contains the certificate chain
        chainSignatureDTO = TemplateUtils.Instantiation.clone(emptySignatureDTO);
        chainSignatureDTO.certificateChainToHex(certificateChain);
        documents[0].setSignatures(new SignatureDTO[] { chainSignatureDTO });

        // PreSign phase - join the content with the certificate chain and evaluate the digest
        try {
            SkdsPreSignRequest req = new SkdsPreSignRequest();
            req.documentsToBase64(documents);
            preSignResp = postJsonRequest(req, SkdsPreSignResponse.class);
            if (ResultCode.valueOf(preSignResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = preSignResp.documentsFromBase64();
                digestSignatureDTO = documents[0].getSignatures()[0];
            } else {
                throw new Exception(preSignResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // signed signature - sign the digest with the smartCard to obtain the digitalSignature
        try {
            fingerPrint = digestSignatureDTO.getDigest().fingerPrintFromHex();
            tracer.info(String.format("fingerPrint:         %s", HexUtils.encodeHex(fingerPrint)));
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            req.setAlias(alias);
            req.setHexDigest(HexUtils.encodeHex(fingerPrint));
            appletResponse = applet.signDigest(req);
            digitalSignature = HexUtils.decodeHex((String) extractJSON(appletResponse));
            tracer.info(String.format("digitalSignature:    %s", HexUtils.encodeHex(digitalSignature)));
            signedSignatureDTO = TemplateUtils.Instantiation.clone(digestSignatureDTO);
            signedSignatureDTO.digitalSignatureToHex(digitalSignature);
            documents[0].getSignatures()[0] = signedSignatureDTO;
        } catch (Exception e) {
            tracer.error("error during the digital signature evaluation", e);
            throw e;
        }

        // PostSign phase - add the digitalSignature to the envelope and store the result into the JCLResultDTO
        try {
            SkdsPostSignRequest req = new SkdsPostSignRequest();
            req.documentsToBase64(documents);
            postSignResp = postJsonRequest(req, SkdsPostSignResponse.class);
            if (ResultCode.valueOf(postSignResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = postSignResp.documentsFromBase64();
                finalizedSignatureDTO = documents[0].getSignatures()[0];
            } else {
                throw new Exception(postSignResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the envelope generation", e);
            throw e;
        }

        //         // Verify phase - load the envelope content and verify the nested signature 
        //         try {
        //            jsonResp = signatureService.verify ( envelopeHex, null, null, VerifyResult.VALID.name() );
        //            verifyDTO = extractResult ( VerifyDTO.class, jsonResp );
        //         } catch(Exception e) {
        //            tracer.error("error during the envelope verification", e);
        //            throw e;
        //         }
        //         
        //         // finalized signature - enveloped signed and eventually marked, not modifiable anymore
        //         try {
        //            verifyResult = (VerifyInfo) converter.toVerifyInfo( verifyDTO );
        //         } catch(Exception e) {
        //            tracer.error("unable to obtain the verifyInfo from the DTO", e);
        //            throw e;
        //         }
        //         
        //         try {
        //            for(VerifiedSignature < ?, ?, VerifyResult, ?> verifiedSignature : verifyResult.getSignatures() ) {
        //               tracer.info(String.format ( "signature validity:  %s", verifiedSignature.getVerifyResult().name() ));
        //               tracer.info(String.format ( "signature type:      %s", verifiedSignature.getSignType().name() ));
        //               tracer.info(String.format ( "disposition:         %s", verifiedSignature.getDisposition().name() ));
        //               tracer.info(String.format ( "digest algorithm:    %s", verifiedSignature.getDigest().getAlgorithm().name() ));
        //               tracer.info(String.format ( "finger print:        %s", HexUtils.encodeHex(verifiedSignature.getDigest().getFingerPrint()) ));
        //               tracer.info(String.format ( "counter signature:   %s", verifiedSignature.isCounterSignature() ));
        //               tracer.info(String.format ( "signature algorithm: %s", verifiedSignature.getSignAlgorithm().name() ));
        //               tracer.info(String.format ( "digital signature:   %s", HexUtils.encodeHex(verifiedSignature.getDigitalSignature()) ));
        //               tracer.info(String.format ( "reason:              %s", verifiedSignature.getReason() ));
        //               tracer.info(String.format ( "signing location:    %s", verifiedSignature.getLocation() ));
        //               tracer.info(String.format ( "signing time:        %s", formatDate(verifiedSignature.getSigningTime()) ));
        //               tracer.info(String.format ( "\n "));
        //               tracer.info(String.format ( "signing certificate chain: "));
        //               for ( X509Certificate cert : verifiedSignature.getRawX509Certificates() ) {
        //                  showCertificate(cert);
        //               }
        //               if ( verifiedSignature.getTimeStamps() != null ) {
        //                  tracer.info(String.format ( "\n "));
        //                  tracer.info(String.format ( "timestamps: "));
        //                  for ( TimeStampInfo mark : verifiedSignature.getTimeStamps() ) {
        //                     tracer.info(String.format ( "timestamp validity:  %s", mark.getVerifyResult().name() ));
        //                     tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() ));
        //                     tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() ));
        //                     tracer.info(String.format ( "message imprint alg: %s", mark.getMessageInprintInfo().getAlgorithm().name() ));
        //                     tracer.info(String.format ( "message imprint:     %s", HexUtils.encodeHex(mark.getMessageInprintInfo().getFingerPrint()) ));
        //                     tracer.info(String.format ( "digest algorithm:    %s", mark.getDigestAlgorithm().name() ));
        //                     tracer.info(String.format ( "digital signature:   %s", HexUtils.encodeHex(mark.getDigitalSignature()) ));
        //                     tracer.info(String.format ( "signature algorithm: %s", mark.getSignAlgorithm().name() ));
        //                     tracer.info(String.format ( "timestamp certificate: "));
        //                     for ( X509Certificate cert : mark.getRawX509Certificates() ) {
        //                        showCertificate(cert);
        //                     }
        //                  }
        //               }
        //            }
        //         } catch(Exception e) {
        //            tracer.error("unable to print the verify results", e);
        //            throw e;
        //         }
        //         
    } finally {
        applet.close();
    }
}

From source file:org.openhealthtools.openatna.net.MailConnection.java

public MimeBodyPart decryptMessage(Message message) throws MessagingException {

    try {//  ww w.jav  a 2s .  c o m
        /* Add BC */
        Security.addProvider(new BouncyCastleProvider());
        // Open the key store
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray());

        // find the certificate for the private key and generate a
        // suitable recipient identifier.
        X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias());
        RecipientId recId = new RecipientId();

        recId.setSerialNumber(cert.getSerialNumber());
        recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

        SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);
        RecipientInformationStore recipients = m.getRecipientInfos();
        // TODO figure out why this doesn't work...
        //RecipientInformation        recipient = recipients.get(recId);
        RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();

        Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray());
        byte[] byteContent = recipient.getContent(key, "BC");
        MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent);
        return res;

    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}