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 testLocale() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.setLocale(Locale.FRENCH);
    beIDKeyStoreParameter.setLogger(new TestLogger());
    keyStore.load(beIDKeyStoreParameter);

    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Signature", null);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);/*from  w  w w .  j  a  va  2s  .  c  o m*/

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);/*  w ww . ja  va  2  s .  com*/
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry,
                context.getBean(WebSocketPskFrameProcessor.class));

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java

public static KeyPair generateRandomKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(2048, new SecureRandom());
    return keyPairGenerator.generateKeyPair();
}

From source file:com.intuit.tank.proxy.ProxyApp.java

public static void main(String[] args) {
    if (StringUtils.isBlank(System.getProperty("jsse.enableSNIExtension"))) {
        System.setProperty("jsse.enableSNIExtension", "false");
    }// www  .  j a v a  2 s.  c  o m
    if (StringUtils.isBlank(System.getProperty("https.protocols"))) {
        System.setProperty("https.protocols", "TLSv1,SSLv3");
    }
    Security.addProvider(new BouncyCastleProvider()); // add it
    new ProxyApp();
}

From source file:com.indivica.olis.Driver.java

public static String signData(String data) {
    X509Certificate cert = null;//from   w  w  w  .  j a  v  a  2s  .c o m
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = "Olis2011";
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        Enumeration e = keystore.aliases();
        String name = "";

        if (e != null) {
            while (e.hasMoreElements()) {
                String n = (String) e.nextElement();
                if (keystore.isKeyEntry(n)) {
                    name = n;
                }
            }
        }

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());
        cert = (X509Certificate) keystore.getCertificate(name);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:org.alfresco.repo.security.authentication.ntlm.NTLMAuthenticationProvider.java

/**
 * Set the JCE provider//from ww w  .  ja v a 2 s  .  c  o m
 * 
 * @param providerClass String
 */
public final void setJCEProvider(String providerClass) {
    // Set the JCE provider, required to provide various encryption/hashing algorithms not available
    // in the standard Sun JDK/JRE

    try {

        // Load the JCE provider class and validate

        Object jceObj = Class.forName(providerClass).newInstance();
        if (jceObj instanceof java.security.Provider) {

            // Inform listeners, validate the configuration change

            Provider jceProvider = (Provider) jceObj;

            // Add the JCE provider

            Security.addProvider(jceProvider);

            // Debug

            if (logger.isDebugEnabled())
                logger.debug("Using JCE provider " + providerClass);
        } else {
            throw new AlfrescoRuntimeException("JCE provider class is not a valid Provider class");
        }
    } catch (ClassNotFoundException ex) {
        throw new AlfrescoRuntimeException("JCE provider class " + providerClass + " not found");
    } catch (Exception ex) {
        throw new AlfrescoRuntimeException("JCE provider class error", ex);
    }
}

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

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

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    final BeIDCard beIDCard = getBeIDCard();
    keyStoreParameter.setBeIDCard(beIDCard);
    keyStoreParameter.setLogoff(true);/*from ww  w  .  j a  v  a2s.  c  om*/
    keyStore.load(keyStoreParameter);

    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    assertEquals(2, keyStore.size());

    assertTrue(keyStore.containsAlias("Signature"));
    assertTrue(keyStore.containsAlias("Authentication"));
    assertNotNull(keyStore.getCreationDate("Signature"));
    assertNotNull(keyStore.getCreationDate("Authentication"));

    assertTrue(keyStore.isKeyEntry("Signature"));
    final X509Certificate signCertificate = (X509Certificate) keyStore.getCertificate("Signature");
    assertNotNull(signCertificate);

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);

    assertNotNull(keyStore.getCertificateChain("Signature"));
    assertNotNull(keyStore.getCertificateChain("Authentication"));

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    assertNotNull(authnPrivateKey);

    assertTrue(keyStore.isKeyEntry("Signature"));
    final PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    assertNotNull(signPrivateKey);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", signPrivateKey, signCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());

    Security.addProvider(new BouncyCastleProvider());

    verifySignatureAlgorithm("SHA1withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {

    final CommandLineParser parser = new GnuParser();
    try {//from   w w w . j ava2  s. c  o m
        final CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            out.println(usage(options));
            return CommandLineInterface.RETURN_SUCCESS;
        }
        if (cmd.hasOption("url")) {
            urlstring = cmd.getOptionValue("url");
        }
        if (cmd.hasOption("instr")) {
            instring = cmd.getOptionValue("instr");
        }
        if (cmd.hasOption("infile")) {
            infilestring = cmd.getOptionValue("infile");
        }
        if (cmd.hasOption("outrep")) {
            outrepstring = cmd.getOptionValue("outrep");
        }
        if (cmd.hasOption("inrep")) {
            inrepstring = cmd.getOptionValue("inrep");
        }
        if (cmd.hasOption("signerfile")) {
            signerfilestring = cmd.getOptionValue("signerfile");
        }
        if (cmd.hasOption("outreq")) {
            outreqstring = cmd.getOptionValue("outreq");
        }
        if (cmd.hasOption("base64")) {
            base64 = true;
        }
        if (cmd.hasOption("verify")) {
            verify = true;
        }
        if (cmd.hasOption("print")) {
            print = true;
        }
        if (cmd.hasOption("inreq")) {
            inreqstring = cmd.getOptionValue("inreq");
        }
        if (cmd.hasOption("sleep")) {
            sleep = Integer.parseInt(cmd.getOptionValue("sleep"));
        }
        final String[] strargs = cmd.getArgs();
        if (strargs.length > 0) {
            urlstring = strargs[PARAM_URL];
        }
        if (cmd.hasOption("certreq")) {
            certReq = true;
        }
        if (cmd.hasOption("reqpolicy")) {
            reqPolicy = cmd.getOptionValue("reqpolicy");
        }

        try {
            final ConsolePasswordReader passwordReader = createConsolePasswordReader();
            keyStoreOptions.parseCommandLine(cmd, passwordReader, out);

            // TODO: Add when implementing username/password auth support:
            // Prompt for user password if not given
            //if (username != null && password == null) {
            //    out.print("Password for user '" + username + "': ");
            //    out.flush();
            //    password = new String(passwordReader.readPassword());
            //}
        } catch (IOException ex) {
            throw new IllegalCommandArgumentsException("Failed to read password: " + ex.getLocalizedMessage());
        }

        if (print && inreqstring == null && inrepstring == null) {
            LOG.error("Missing -inreq or -inrep");
            out.println(usage(options));
            return CommandLineInterface.RETURN_INVALID_ARGUMENTS;
        }

        if (args.length < 1) {
            out.println(usage(options));
            return CommandLineInterface.RETURN_INVALID_ARGUMENTS;
        } else if (urlstring == null && !verify && !print) {
            LOG.error("Missing URL");
            out.println(usage(options));
            return CommandLineInterface.RETURN_INVALID_ARGUMENTS;
        } else {
            keyStoreOptions.validateOptions();

            if (Security.addProvider(new BouncyCastleProvider()) < 0) {
                LOG.error("Could not install BC provider");
                // If already installed, remove so we can handle redeploy
                Security.removeProvider("BC");
                if (Security.addProvider(new BouncyCastleProvider()) < 0) {
                    LOG.error("Cannot even install BC provider again!");
                }
            }

            run();
            return CommandLineInterface.RETURN_SUCCESS;
        }
    } catch (ParseException e) {
        // oops, something went wrong
        out.println(usage(options));
        return CommandLineInterface.RETURN_INVALID_ARGUMENTS;
    } catch (Exception ex) {
        throw new UnexpectedCommandFailureException(ex);
    }
}

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

public CMSSignedData SignedData(Element InputDocument) {

    try {/*from   w  w w  .jav  a 2 s  .c om*/
        X509Certificate cert = getCertificate();
        PrivateKey privatekey = getPrivateKey();
        if (privatekey == null) {
            return null;
        } else {
            String Document = PrepareDocumentToBeSign(InputDocument);
            System.out.println(Document);
            System.out.println("Certificate loaded");
            // define the provider Bouncy castle  
            if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
                Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            }

            //register the user certificate in the collection 
            ArrayList certList = new ArrayList();
            certList.add(cert);
            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    "BC");

            System.out.println("provider loaded");
            // create the CMSSignedData
            CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
            System.out.println("CMS created");
            signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
            signGen.addCertificatesAndCRLs(certs);
            System.out.println("Signer loaded");

            CMSProcessable content = new CMSProcessableByteArray(Document.getBytes());
            System.out.println("BytesArray loaded");
            // the second variable "true" means that the content will be wrap with the signature
            return signGen.generate(content, true, "BC");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

public CredentialManagerImpl() throws CMException {
    /*/*from w  ww .  j a  v a  2 s  .co  m*/
     * Make sure we have BouncyCastle provider installed, just in case
     * (needed for some tests and reading PKCS#12 keystores)
     */
    Security.addProvider(new BouncyCastleProvider());

    /*
     * Open the files stored in the (DEFAULT!!!) Credential Manager's
     * directory
     */
    // loadDefaultConfigurationFiles();
    // FIXME
    /*
     * Get the location of the directory containing the Keystore and
     * Truststore somehow - from OSGi's Configuration Service
     */

    // initialize();
}