Example usage for java.security SecureRandom SecureRandom

List of usage examples for java.security SecureRandom SecureRandom

Introduction

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

Prototype

public SecureRandom() 

Source Link

Document

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

Usage

From source file:com.example.ExerciseMe.tvmclient.AmazonTVMClient.java

/**
 * Creates a 128-bit random string./*w  w w  .java 2s  .c o  m*/
 */
public String generateRandomString() {
    SecureRandom random = new SecureRandom();
    byte[] randomBytes = random.generateSeed(16);
    return new String(Hex.encodeHex(randomBytes));
}

From source file:com.ad.mediasharing.tvmclient.AmazonTVMClient.java

/**
 * Creates a 128-bit random string./*from  www . j av a2s . co  m*/
 */
public String generateRandomString() {
    SecureRandom random = new SecureRandom();
    byte[] randomBytes = random.generateSeed(16);
    String randomString = new String(Hex.encodeHex(randomBytes));
    return randomString;
}

From source file:fr.paris.lutece.portal.web.admin.AdminPageJspBeanTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    _randomPageName = "page" + new SecureRandom().nextLong();
    IPageService pageService = (IPageService) SpringContextService.getBean("pageService");
    _page = new Page();
    _page.setParentPageId(PortalService.getRootPageId());
    _page.setPageTemplateId(PageTemplateHome.getPageTemplatesList().get(0).getId());
    _page.setName(_randomPageName);//from  ww  w.  j av  a 2s  . co m
    _page.setDescription(_randomPageName);
    _page.setMetaKeywords("");
    _page.setMetaDescription("");
    _page.setNodeStatus(1);
    _page.setDateUpdate(new Timestamp(new java.util.Date().getTime()));
    _page.setDisplayDateUpdate(true);
    _page.setIsManualDateUpdate(true);
    pageService.createPage(_page);
    _bean = new AdminPageJspBean();
    _adminUser = getAdminUser();
}

From source file:my.adam.smo.EncryptionTest.java

@Test
public void asymmetricRequestEncryptionTest() {
    ApplicationContext clientContext = new ClassPathXmlApplicationContext("Context.xml");
    HTTPServer s = clientContext.getBean(HTTPServer.class);

    SecureRandom secureRandom = new SecureRandom();

    RPCommunication.Response response = RPCommunication.Response.newBuilder().setException("").setRequestId(1l)
            .setResponse(ByteString.copyFrom(ServerCorrectnessTest.getMegaBytes(10))).build();

    Assert.assertEquals(response.getResponse(),
            s.getAsymDecryptedResponse(s.getAsymEncryptedResponse(response)).getResponse());
    Assert.assertEquals(response.getResponse(),
            s.getDecryptedResponse(s.getEncryptedResponse(response)).getResponse());

    RPCommunication.Request request = RPCommunication.Request.newBuilder()
            .setMethodArgument(ByteString.copyFrom(ServerCorrectnessTest.getMegaBytes(10))).setMethodName("ala")
            .setRequestId(1l).setServiceName("ola").build();

    Assert.assertEquals(request.getMethodArgument(),
            s.getAsymDecryptedRequest(s.getAsymEncryptedRequest(request)).getMethodArgument());
    Assert.assertEquals(request.getMethodArgument(),
            s.getDecryptedRequest(s.getEncryptedRequest(request)).getMethodArgument());
}

From source file:cybervillains.ca.KeyStoreManager.java

@SuppressWarnings("unchecked")
public KeyStoreManager(File root) {
    this.root = root;

    Security.insertProviderAt(new BouncyCastleProvider(), 2);

    _sr = new SecureRandom();

    try {/*from w  w w  .j  a  v  a 2 s  . c  om*/
        _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO);
        _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO);
    } catch (Throwable t) {
        throw new Error(t);
    }

    try {

        File privKeys = new File(root, KEYMAP_SER_FILE);

        if (!privKeys.exists()) {
            _rememberedPrivateKeys = new HashMap<PublicKey, PrivateKey>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys));
            // Deserialize the object
            _rememberedPrivateKeys = (HashMap<PublicKey, PrivateKey>) in.readObject();
            in.close();
        }

        File pubKeys = new File(root, PUB_KEYMAP_SER_FILE);

        if (!pubKeys.exists()) {
            _mappedPublicKeys = new HashMap<PublicKey, PublicKey>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys));
            // Deserialize the object
            _mappedPublicKeys = (HashMap<PublicKey, PublicKey>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // check for file exists, won't happen.
        e.printStackTrace();
    } catch (IOException e) {
        // we could correct, but this probably indicates a corruption
        // of the serialized file that we want to know about; likely
        // synchronization problems during serialization.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // serious problem.
        e.printStackTrace();
        throw new Error(e);
    }

    _rsaKpg.initialize(1024, _sr);
    _dsaKpg.initialize(1024, _sr);

    try {
        _ks = KeyStore.getInstance("JKS");

        reloadKeystore();
    } catch (FileNotFoundException fnfe) {
        try {
            createKeystore();
        } catch (Exception e) {
            throw new Error(e);
        }
    } catch (Exception e) {
        throw new Error(e);
    }

    try {

        File file = new File(root, CERTMAP_SER_FILE);

        if (!file.exists()) {
            _certMap = new HashMap<String, String>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            _certMap = (HashMap<String, String>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // won't happen, check file.exists()
        e.printStackTrace();
    } catch (IOException e) {
        // corrupted file, we want to know.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // something very wrong, exit
        e.printStackTrace();
        throw new Error(e);
    }

    try {

        File file = new File(root, SUBJMAP_SER_FILE);

        if (!file.exists()) {
            _subjectMap = new HashMap<String, String>();
        } else {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            _subjectMap = (HashMap<String, String>) in.readObject();
            in.close();
        }

    } catch (FileNotFoundException e) {
        // won't happen, check file.exists()
        e.printStackTrace();
    } catch (IOException e) {
        // corrupted file, we want to know.
        e.printStackTrace();
        throw new Error(e);
    } catch (ClassNotFoundException e) {
        // something very wrong, exit
        e.printStackTrace();
        throw new Error(e);
    }

}

From source file:dualcontrol.CryptoHandler.java

private byte[] getIvBytes(String ivString) {
    if (ivString.length() > 2) {
        return Base64.decodeBase64(ivString);
    }// w  w  w .ja  v a2 s  .  com
    int ivLength = Integer.parseInt(ivString);
    this.ivBytes = new byte[ivLength];
    new SecureRandom().nextBytes(ivBytes);
    return ivBytes;
}

From source file:com.villemos.ispace.webster.WebsterProducer.java

public void process(Exchange exchange) throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {/*from w w w.  ja  va 2s  . c om*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getWebsterEndpoint().getProxyHost();
    Integer proxyPort = getWebsterEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getWebsterEndpoint().getAuthenticationUser() != null
            && getWebsterEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()),
                new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(),
                        getWebsterEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/"
            + getWebsterEndpoint().getPath();
    if (getWebsterEndpoint().getPort() != 80) {
        uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath();
    }

    /** Break the query into its elements and search for each. */
    for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) {
        uriStr += "/" + word;
        URI uri = new URI(uriStr);

        if (getWebsterEndpoint().getPort() != 80) {
            target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(),
                    getWebsterEndpoint().getProtocol());
        } else {
            target = new HttpHost(getWebsterEndpoint().getDomain());
        }
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpUriRequest method = new HttpGet(uri);
        HttpResponse response = client.execute(target, method, localContext);

        if (response.getStatusLine().getStatusCode() == 200) {
            /** Extract result. */
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            ResultSet set = new ResultSet();

            Matcher matcher = pattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " ");

                /** Create ResultSet*/
                InformationObject io = new InformationObject();
                io.hasUri = uriStr;
                io.fromSource = "Webster";
                io.hasTitle = "Webster definition of '" + word + "'.";
                io.ofEntityType = "Definition";
                io.ofMimeType = "text/html";
                io.withRawText = result;
                io.score = 20;
                set.informationobjects.add(io);
            }

            matcher = spellPattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1);
                String[] elements = result.split("<li><a href=.*?>");

                for (String element : elements) {
                    if (element.trim().equals("") == false) {
                        set.suggestions
                                .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster"));
                    }
                }
            }

            if (exchange.getIn().getHeader(SolrOptions.stream) != null) {

                for (InformationObject io : set.informationobjects) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(io);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }

                for (Suggestion suggestion : set.suggestions) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(suggestion);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }
            } else {
                exchange.getOut().setBody(set);
            }
        } else {
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            System.out.println(page);
        }
    }
}

From source file:org.apache.cloudstack.cloudian.client.CloudianClient.java

public CloudianClient(final String host, final Integer port, final String scheme, final String username,
        final String password, final boolean validateSSlCertificate, final int timeout)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    final HttpHost adminHost = new HttpHost(host, port, scheme);
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(adminHost, new BasicScheme());

    this.adminApiUrl = adminHost.toURI();
    this.httpContext = HttpClientContext.create();
    this.httpContext.setCredentialsProvider(provider);
    this.httpContext.setAuthCache(authCache);

    final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
            .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();

    if (!validateSSlCertificate) {
        final SSLContext sslcontext = SSLUtils.getSSLContext();
        sslcontext.init(null, new X509TrustManager[] { new TrustAllManager() }, new SecureRandom());
        final SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
    } else {/*w w  w. j av  a 2 s . com*/
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config).build();
    }
}

From source file:evaluation.loadGenerator.fixedSchedule.ALM_FS_Poisson.java

public ALM_FS_Poisson(AL_FixedScheduleLoadGenerator owner) {
    this.settings = owner.getSettings();
    this.experimentStart = owner.getScheduler().now() + TimeUnit.SECONDS.toNanos(2);
    this.startOfPeriod = experimentStart;
    int numberOfClients = settings.getPropertyAsInt("AL-POISSON-NUMBER_OF_CLIENTS");
    String str_avgSendsPerPulse = settings.getProperty("AL-POISSON-AVERAGE_SEND_OPERATIONS_PER_PULSE");
    if (RandomVariable.isRandomVariable(str_avgSendsPerPulse)) {
        this.AVG_SENDS_PER_PERIOD = RandomVariable.createRandomVariable(str_avgSendsPerPulse);
    } else {/*  w w  w.  ja v a 2 s .c  o  m*/
        float float_avgSendsPerPulse = Float.parseFloat(str_avgSendsPerPulse);
        float_avgSendsPerPulse = float_avgSendsPerPulse * (float) numberOfClients;
        if (float_avgSendsPerPulse < 1f)
            this.AVG_SENDS_PER_PERIOD = new FakeRandom(1);
        else
            this.AVG_SENDS_PER_PERIOD = new FakeRandom(Math.round(float_avgSendsPerPulse));
    }
    String str_ReplyDelay = settings.getProperty("AL-POISSON-REPLY_DELAY");
    if (RandomVariable.isRandomVariable(str_ReplyDelay))
        this.REPLY_DELAY = RandomVariable.createRandomVariable(str_ReplyDelay);
    else
        this.REPLY_DELAY = new FakeRandom(Double.parseDouble(str_ReplyDelay));
    this.PULSE_LENGTH = (long) (settings.getPropertyAsFloat("AL-POISSON-PULSE_LENGTH") * 1000000000f);
    this.random = new SecureRandom();
    this.randomDataImpl = new RandomDataImpl();
    this.randomDataImpl.reSeed(this.random.nextLong());
    System.out.println("LOAD_GENERATOR: start at " + experimentStart);
    // create client
    owner.getLoadGenerator().commandLineParameters.gMixTool = ToolName.CLIENT;
    this.client = new AnonNode(owner.getLoadGenerator().commandLineParameters);
    this.scheduleTarget = new ALRR_BasicWriter(this, client.IS_DUPLEX);
    // determine number of clients and lines; create ClientWrapper objects etc
    this.clientsArray = new ALRR_ClientWrapper[numberOfClients];
    CommunicationDirection cm = client.IS_DUPLEX ? CommunicationDirection.DUPLEX
            : CommunicationDirection.SIMPLEX_SENDER;
    int port = settings.getPropertyAsInt("SERVICE_PORT1");
    System.out.println("LOAD_GENERATOR: connecting clients...");
    for (int i = 0; i < numberOfClients; i++) {
        clientsArray[i] = new ALRR_ClientWrapper(i);
        clientsArray[i].socket = client.createStreamSocket(cm, client.ROUTING_MODE != RoutingMode.CASCADE);
        try {
            clientsArray[i].socket.connect(port);
            clientsArray[i].outputStream = new BufferedOutputStream(clientsArray[i].socket.getOutputStream());
            if (client.IS_DUPLEX)
                clientsArray[i].inputStream = clientsArray[i].socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String str_requestPayloadSize = settings.getProperty("AL-POISSON-REQUEST_PAYLOAD_SIZE");
    if (RandomVariable.isRandomVariable(str_requestPayloadSize)) {
        this.REQUEST_PAYLOAD_SIZE = RandomVariable.createRandomVariable(str_requestPayloadSize);
    } else {
        if (str_requestPayloadSize.equalsIgnoreCase("AUTO"))
            this.REQUEST_PAYLOAD_SIZE = new FakeRandom(clientsArray[0].socket.getMTU());
        else
            this.REQUEST_PAYLOAD_SIZE = new FakeRandom(Integer.parseInt(str_requestPayloadSize));
    }
    String str_replyPayloadSize = settings.getProperty("AL-POISSON-REPLY_PAYLOAD_SIZE");
    if (RandomVariable.isRandomVariable(str_replyPayloadSize)) {
        this.REPLY_PAYLOAD_SIZE = RandomVariable.createRandomVariable(str_replyPayloadSize);
    } else {
        if (str_replyPayloadSize.equalsIgnoreCase("AUTO"))
            this.REPLY_PAYLOAD_SIZE = new FakeRandom(clientsArray[0].socket.getMTU());
        else
            this.REPLY_PAYLOAD_SIZE = new FakeRandom(Integer.parseInt(str_replyPayloadSize));
    }
    if (client.IS_DUPLEX) {
        this.replyReceiver = new ALRR_ReplyReceiver(clientsArray, settings);
        //this.replyReceiver.registerObserver(this);
        this.replyReceiver.start();
    }
}

From source file:org.apache.camel.component.box.internal.LoginAuthFlowUI.java

@SuppressWarnings("deprecation")
@Override//from w  w  w . jav a 2  s  .  c om
public void authenticate(IAuthFlowListener listener) {

    // TODO run this on an Executor to make it async

    // create HtmlUnit client
    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
    final WebClientOptions options = webClient.getOptions();
    options.setRedirectEnabled(true);
    options.setJavaScriptEnabled(false);
    options.setThrowExceptionOnFailingStatusCode(true);
    options.setThrowExceptionOnScriptError(true);
    options.setPrintContentOnFailingStatusCode(LOG.isDebugEnabled());

    // add HTTP proxy if set
    final Map<String, Object> httpParams = configuration.getHttpParams();
    if (httpParams != null && httpParams.get(ConnRoutePNames.DEFAULT_PROXY) != null) {
        final HttpHost proxyHost = (HttpHost) httpParams.get(ConnRoutePNames.DEFAULT_PROXY);
        final Boolean socksProxy = (Boolean) httpParams.get("http.route.socks-proxy");
        final ProxyConfig proxyConfig = new ProxyConfig(proxyHost.getHostName(), proxyHost.getPort(),
                socksProxy != null ? socksProxy : false);
        options.setProxyConfig(proxyConfig);
    }

    // authorize application on user's behalf
    try {
        final String csrfId = String.valueOf(new SecureRandom().nextLong());

        OAuthWebViewData viewData = new OAuthWebViewData(boxClient.getOAuthDataController());
        viewData.setOptionalState(String.valueOf(csrfId));
        final HtmlPage authPage = webClient.getPage(viewData.buildUrl().toString());

        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("login_form");
        final HtmlTextInput login = loginForm.getInputByName("login");
        login.setText(configuration.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("password");
        password.setText(configuration.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("login_submit");

        // submit consent
        final HtmlPage consentPage = submitInput.click();
        final HtmlForm consentForm = consentPage.getFormByName("consent_form");
        final HtmlButton consentAccept = consentForm.getButtonByName("consent_accept");

        // disable redirect to avoid loading redirect URL
        webClient.getOptions().setRedirectEnabled(false);

        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = consentAccept.click();
            redirectQuery = redirectPage.getUrl().getQuery();
        } catch (FailingHttpStatusCodeException e) {
            // escalate non redirect errors
            if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw e;
            }
            final String location = e.getResponse().getResponseHeaderValue("Location");
            redirectQuery = location.substring(location.indexOf('?') + 1);
        }
        final Map<String, String> params = new HashMap<String, String>();
        final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
        while (matcher.find()) {
            params.put(matcher.group(1), matcher.group(2));
        }
        final String state = params.get("state");
        if (!csrfId.equals(state)) {
            final SecurityException e = new SecurityException("Invalid CSRF code!");
            listener.onAuthFlowException(e);
            this.listener.onAuthFlowException(e);
        } else {

            // get authorization code
            final String authorizationCode = params.get("code");

            // get OAuth token
            final IBoxOAuthManager oAuthManager = boxClient.getOAuthManager();
            final BoxOAuthToken oAuthToken = oAuthManager.createOAuth(authorizationCode,
                    configuration.getClientId(), configuration.getClientSecret(), null);

            // send initial token to BoxClient and this.listener
            final OAuthDataMessage authDataMessage = new OAuthDataMessage(oAuthToken, boxClient.getJSONParser(),
                    boxClient.getResourceHub());
            listener.onAuthFlowEvent(OAuthEvent.OAUTH_CREATED, authDataMessage);
            this.listener.onAuthFlowEvent(OAuthEvent.OAUTH_CREATED, authDataMessage);
        }

    } catch (Exception e) {
        // forward login exceptions to listener
        listener.onAuthFlowException(e);
        this.listener.onAuthFlowException(e);
    }
}