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.allstate.client.ssl.SSLUtils.java

public static SSLSocketFactory getFactory(Security security) throws GeneralSecurityException {
    X509HostnameVerifier verifier = security.isStrictHostVerification()
            ? SSLSocketFactory.STRICT_HOSTNAME_VERIFIER
            : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(security.getSslContextProtocol(),
            security.getKeyStore(), security.getKeyStorePasswordAsString(), security.getTrustStore(),
            new SecureRandom(), null, verifier);
    return socketFactory;
}

From source file:cl.whyem.testsutilityproject.otpgenerator.KeyBase.java

protected byte[] randomBytes(int count) {
    SecureRandom random = new SecureRandom();
    byte[] buf = new byte[count];
    random.nextBytes(buf);/*w w w.j  a v  a 2  s  .c  om*/
    return buf;
}

From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java

public static boolean checkHttpsURLStatus(final String url) {
    boolean https_StatusFlag = false;
    System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>");

    URL httpsurl;//from w  w  w . j  ava2 s. com
    try {

        // Create a context that doesn't check certificates.
        SSLContext ssl_ctx = SSLContext.getInstance("TLS");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, // key manager
                trust_mgr, // trust manager
                new SecureRandom()); // random number generator
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        System.out.println("Url =========" + url);
        httpsurl = new URL(url);

        HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection();
        con.setHostnameVerifier(DO_NOT_VERIFY);
        int statusCode = con.getResponseCode();
        System.out.println("statusCode =========" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK) {

            https_StatusFlag = true;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return https_StatusFlag;
}

From source file:com.google.gwtjsonrpc.server.SignedToken.java

/**
 * Create a new utility, using the specific key.
 * //from  w w w  .  ja v  a2s  .  c  o  m
 * @param age the number of seconds a token may remain valid.
 * @param keyBase64 base 64 encoded representation of the key.
 * @throws XsrfException the JVM doesn't support the necessary algorithms.
 */
public SignedToken(final int age, final String keyBase64) throws XsrfException {
    maxAge = age > 5 ? age / 5 : age;
    key = new SecretKeySpec(decodeBase64(keyBase64), MAC_ALG);
    rng = new SecureRandom();
    tokenLength = 2 * INT_SZ + newMac().getMacLength();
}

From source file:fr.acxio.tools.agia.file.pdf.SplitPDFTaskletTest.java

@Test
public void testSplit() throws Exception {
    SplitPDFTasklet aTasklet = new SplitPDFTasklet();

    PageSplittingPDDocumentFactory aDocumentFactory = new PageSplittingPDDocumentFactory();
    aDocumentFactory.setSplitAtPage(1);/*w w  w  . ja v  a 2s.c o m*/
    aTasklet.setDocumentFactory(aDocumentFactory);

    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:src/test/resources/testFiles/content*.pdf");

    aTasklet.setSourceFactory(aSourceFactory);

    StandardEvaluationContextFactory aContextFactory = new StandardEvaluationContextFactory();

    Map<String, Object> aCommonObjects = new HashMap<String, Object>();
    aCommonObjects.put("fu", new FilenameUtils());

    DateToStringConverter aDTSConverter = new DateToStringConverter();
    aDTSConverter.setDestinationPattern("yyyyMMddhhmmssSSS");

    aCommonObjects.put("dc", aDTSConverter);

    aCommonObjects.put("sr", new SecureRandom());

    aContextFactory.setCommonObjects(aCommonObjects);

    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setEvaluationContextFactory(aContextFactory);
    aDestinationFactory.setExpression(
            "target/ST-N-@{#fu.getBaseName(#in.SOURCE.filename)}-@{#dc.convert(new java.util.Date())}-@{#sr.nextInt(10000)}.pdf");

    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setForceReplace(false);

    StepContribution aStepContribution = mock(StepContribution.class);

    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));

    Collection<File> aFilesTocheck = FileUtils.listFiles(new File("target"),
            new WildcardFileFilter("ST-N-*.pdf"), null);
    assertEquals(4, aFilesTocheck.size());

    verify(aStepContribution, times(2)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1); // content1.pdf
    verify(aStepContribution, times(1)).incrementWriteCount(3); // content2.pdf
}

From source file:com.POLIS.licensing.frontend.AnnotationEnabledFrontendTest.java

@Before
public void setUp()
        throws NoSuchAlgorithmException, NoSuchProviderException, SystemStateException, OperationException {
    frontend = new AnnotationEnabledFrontend<>(new TestFactory(), new TestConnector(), new TestDecorator());

    SecureRandom random = new SecureRandom();
    KeyPairGenerator rsagenerator = KeyPairGenerator.getInstance("RSA", "BC");
    rsagenerator.initialize(1024, random);
    KeyPair pair = rsagenerator.generateKeyPair();
    serverPubKey = pair.getPublic();//from   www  . ja v  a 2s. co  m
    serverPrivKey = pair.getPrivate();
    frontend.initialize(serverPubKey);
}

From source file:com.test.controller.ResourceController.java

private static void trustAllHttpsCertificates() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        //            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        //                return null;
        //            }
        ///*from   ww w  . j a va2 s  .  c  o m*/
        //            public void checkClientTrusted(X509Certificate[] certs, String authType) {
        //            }
        //
        //            public void checkServerTrusted(X509Certificate[] certs, String authType) {
        //            }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            //                return new java.security.cert.X509Certificate[0];  //To change body of implemented methods use File | Settings | File Templates.
            return null;
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        ;
    }

}

From source file:corner.encrypt.services.impl.CipherKey.java

public void createRandomCipher() {
    SecureRandom secureRandom = new SecureRandom();
    Random random = new Random(secureRandom.nextLong());
    cipher = new byte[cipherLen];
    random.nextBytes(cipher);/*  ww  w.j ava2s . c  om*/
    persistCipher();
}

From source file:fi.hsl.parkandride.config.CoreConfiguration.java

String tokenSecret() {
    String secret = tokenSecret;//  www. j  a v a 2  s.c o m
    int minLength = AuthenticationService.SECRET_MIN_LENGTH;
    if (secret.length() < minLength) {
        log.warn("The value of {} is shorter than {} characters; replacing it with a randomly generated value. "
                + "This may cause tokens to expire prematurely.", SECURITY_TOKEN_SECRET, minLength);
        int[] chars = new SecureRandom().ints(minLength).map(i -> (char) i).toArray();
        return new String(chars, 0, chars.length);
    } else {
        return secret;
    }
}

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void symetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(256, new SecureRandom());
    Key k = kg.generateKey();//from w  ww .  j a  v a2s.co m

    Cipher c = Cipher.getInstance("AES");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, k);
    c.update(plainBytes);

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, k);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}