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.kegare.caveworld.world.WorldProviderCaveworld.java

public static void loadDimData(NBTTagCompound data) {
    if (!data.hasKey("Seed")) {
        data.setLong("Seed", new SecureRandom().nextLong());
    }//w w  w .  j  a v  a 2  s.  com

    if (!data.hasKey("SubsurfaceHeight")) {
        data.setInteger("SubsurfaceHeight", Config.subsurfaceHeight);
    }

    dimensionSeed = data.getLong("Seed");
    subsurfaceHeight = data.getInteger("SubsurfaceHeight");

    NBTTagCompound dat = data.getCompoundTag("TeleportPos");

    if (dat != null) {
        int posX = dat.getInteger("PosX");
        int posY = dat.getInteger("PosY");
        int posZ = dat.getInteger("PosZ");

        recentTeleportPos = new ChunkCoordinates(posX, posY, posZ);
    }
}

From source file:org.cloudfoundry.identity.uaa.login.feature.CreateAccountIT.java

@Test
public void testClientInitiatedSignup() throws Exception {
    String userEmail = "user" + new SecureRandom().nextInt() + "@example.com";

    webDriver.get(baseUrl + "/create_account?client_id=app");

    Assert.assertEquals("Create your account", webDriver.findElement(By.tagName("h1")).getText());

    int receivedEmailSize = simpleSmtpServer.getReceivedEmailSize();

    webDriver.findElement(By.name("email")).sendKeys(userEmail);
    webDriver.findElement(By.name("password")).sendKeys("secret");
    webDriver.findElement(By.name("password_confirmation")).sendKeys("secret");
    webDriver.findElement(By.xpath("//input[@value='Send activation link']")).click();

    Assert.assertEquals(receivedEmailSize + 1, simpleSmtpServer.getReceivedEmailSize());
    Iterator receivedEmail = simpleSmtpServer.getReceivedEmail();
    SmtpMessage message = (SmtpMessage) receivedEmail.next();
    receivedEmail.remove();//from   www . jav a 2s.c  o  m
    Assert.assertEquals(userEmail, message.getHeaderValue("To"));
    Assert.assertThat(message.getBody(), containsString("Activate your account"));

    Assert.assertEquals("Please check email for an activation link.",
            webDriver.findElement(By.cssSelector(".instructions-sent")).getText());

    String link = testClient.extractLink(message.getBody());
    assertFalse(isEmpty(link));

    webDriver.get(link);
    Assert.assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), not(containsString("Where to?")));
}

From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java

public int poll() 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 {/*w w w  . j  av a 2 s . com*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getHttpCrawlerEndpoint().getProxyHost();
    Integer proxyPort = getHttpCrawlerEndpoint().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 (getHttpCrawlerEndpoint().getAuthenticationUser() != null
            && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()),
                new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(),
                        getHttpCrawlerEndpoint().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 = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain();
    if (getHttpCrawlerEndpoint().getPort() != 80) {
        uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath();
    } else {
        uriStr += getHttpCrawlerEndpoint().getPath();
    }
    URI uri = new URI(uriStr);

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

    /** Default boundary is the domain. */
    getHttpCrawlerEndpoint().getBoundaries()
            .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain());

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

    if (response.getStatusLine().getStatusCode() == 200) {
        processSite(uri, response);
    } else if (response.getStatusLine().getStatusCode() == 302) {
        HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpGet get = new HttpGet(target.toURI());
        // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php");

        /** Read the response fully, to clear it. */
        HttpEntity entity = response.getEntity();
        HttpClientConfigurer.readFully(entity.getContent());

        response = client.execute(target, get, localContext);
        processSite(uri, response);
        System.out.println("Final target: " + target);
    } else {
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        System.out.println(HttpClientConfigurer.readFully(instream));
    }

    return 0;
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.http.HttpClientFactory.java

/**
 * Gets a SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SchemeRegistry object.//from w w w  . j a  va2 s. c  o m
 */
private SchemeRegistry getSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    if (sslContext == null) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

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

From source file:com.intel.chimera.StreamCipherTest.java

private void cryptoCipherTestForInputStream(int count, String encCipherClass, String decCipherClass, byte[] iv)
        throws IOException {
    Cipher encCipher = null;/*from  w  ww  . ja  va 2 s.co m*/
    try {
        encCipher = (Cipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCipherClass), props,
                transformation);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto cipher!");
    }
    LOG.info("Created a cipher object of type: " + encCipherClass);

    // Generate data
    SecureRandom random = new SecureRandom();
    byte[] originalData = new byte[count];
    byte[] decryptedData = new byte[count];
    random.nextBytes(originalData);
    LOG.info("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CTRCryptoOutputStream out = new CTRCryptoOutputStream(encryptedData, encCipher, bufferSize, key, iv);
    out.write(originalData, 0, originalData.length);
    out.flush();
    out.close();
    LOG.info("Finished encrypting data");

    Cipher decCipher = null;
    try {
        decCipher = (Cipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCipherClass), props,
                transformation);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto cipher!");
    }
    LOG.info("Created a cipher object of type: " + decCipherClass);

    // Decrypt data
    CTRCryptoInputStream in = new CTRCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()),
            decCipher, bufferSize, key, iv);

    // Check
    int remainingToRead = count;
    int offset = 0;
    while (remainingToRead > 0) {
        int n = in.read(decryptedData, offset, decryptedData.length - offset);
        if (n >= 0) {
            remainingToRead -= n;
            offset += n;
        }
    }

    Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData);

    // Decrypt data byte-at-a-time
    in = new CTRCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher, bufferSize,
            key, iv);

    // Check
    DataInputStream originalIn = new DataInputStream(
            new BufferedInputStream(new ByteArrayInputStream(originalData)));
    int expected;
    do {
        expected = originalIn.read();
        Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read());
    } while (expected != -1);

    LOG.info("SUCCESS! Completed checking " + count + " records");
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

public String getEncryptedMessage(byte[] data) {
    Security.addProvider(new BouncyCastleProvider());

    try {/*from   w  w w  . j  a v  a 2  s.  c o  m*/

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStream out = new ArmoredOutputStream(baos);
        byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP);
        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC"));
        OutputStream cOut = encGen.open(out, compressedData.length);
        cOut.write(compressedData);
        cOut.close();
        out.close();
        baos.flush();
        return new String(baos.toByteArray());
    } catch (PGPException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.cl.roadshow.crypto.AESCtr.java

/**
 * Private encryption method./*from  w  ww.  j av a 2 s.  c o m*/
 * 
 * @param keystring
 * @param message
 * @param bits
 * @return bytearray containing encrypted message
 * @throws Exception
 */
private static byte[] encrypt(String keystring, String message, int bits) throws Exception {
    byte[] encValue = null;
    SecureRandom random = new SecureRandom();
    byte[] nonceBytes = new byte[8];
    random.nextBytes(nonceBytes);
    IvParameterSpec nonce = new IvParameterSpec(Arrays.copyOf(nonceBytes, 16));

    Key key = generateKey(keystring, bits);
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.ENCRYPT_MODE, key, nonce);
    byte[] ciphertextWithoutNonce = c.doFinal(message.getBytes("UTF-8"));
    encValue = Arrays.copyOf(nonceBytes, nonceBytes.length + ciphertextWithoutNonce.length);
    for (int i = 0; i < ciphertextWithoutNonce.length; i++) {
        encValue[i + 8] = ciphertextWithoutNonce[i];
    }

    return encValue;
}

From source file:com.afwsamples.testdpc.safetynet.SafetyNetFragment.java

/**
 * For simplicity, we generate the nonce in the client. However, it should be generated on the
 * server for anti-replay protection.//  w w w  . j a  v a2  s .c om
 */
private byte[] generateNonce() {
    byte[] nonce = new byte[32];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(nonce);
    return nonce;
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;// w  ww.  j a v  a2s.co  m
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}