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:org.cloudfoundry.community.servicebroker.postgresql.service.Role.java

public String bindRoleToDatabase(String dbInstanceId) throws SQLException {
    Utils.checkValidUUID(dbInstanceId);/*  w ww.j  a  va 2s .c  o  m*/

    SecureRandom random = new SecureRandom();
    String passwd = new BigInteger(130, random).toString(32);

    PostgreSQLDatabase.executeUpdate("ALTER ROLE \"" + dbInstanceId + "\" LOGIN password '" + passwd + "'");
    return passwd;
}

From source file:com.example.license.DESUtil.java

/**
 * ?/*from  w w  w.j  a  va  2s  .  com*/
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return ??
 */
public static String encrypt(String data, String key) throws Exception {
    Key deskey = keyGenerator(key);
    // Cipher??
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    SecureRandom random = new SecureRandom();
    // ?Cipher?
    cipher.init(Cipher.ENCRYPT_MODE, deskey, random);
    byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
    // http://tripledes.online-domain-tools.com/??
    for (int i = 0; i < results.length; i++) {
        System.out.print(results[i] + " ");
    }
    System.out.println();
    // ??Base64?
    return Base64.encodeBase64String(results);
}

From source file:com.andiandy.m101j.week2.hw3.SessionDAO.java

public String startSession(String username) {

    // get 32 byte random number. that's a lot of bits.
    SecureRandom generator = new SecureRandom();
    byte randomBytes[] = new byte[32];
    generator.nextBytes(randomBytes);//from w w  w .  j av  a  2 s .co  m

    String sessionID = Base64.encodeBase64(randomBytes).toString();

    // build the BSON object
    BasicDBObject session = new BasicDBObject("username", username);

    session.append("_id", sessionID);

    sessionsCollection.insert(session);

    return session.getString("_id");
}

From source file:com.billing.ng.crypto.util.HashUtils.java

/**
 * Generates a string of random alphanumeric characters of the given length. The generated salt can be
 * used to add entropy to a hashing algorithm or token generator, thus making the result harder to crack.
 *
 * @param length length of salt string to generate
 * @return salt string//from   w  w  w .j av  a  2s. c o  m
 */
public static String generateHashSalt(int length) {
    SecureRandom random = new SecureRandom();

    StringBuffer salt = new StringBuffer(length);
    for (int i = 0; i < length; i++)
        salt.append(chars[random.nextInt(chars.length)]);

    return salt.toString();
}

From source file:com.assignment4.security.SaltFilter.java

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

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

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

    if (csrfPreventionSaltCache == null) {
        csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(5000)
                .expireAfterWrite(20, TimeUnit.MINUTES).build();

        httpReq.getSession().setAttribute("csrfPreventionSaltCache", csrfPreventionSaltCache);
    }//from w  w w .j  av a 2  s  . c o  m

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

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

    chain.doFilter(request, response);
}

From source file:com.boubei.tss.modules.license.LicenseFactory.java

/**
 * ???/*from  w ww  .  j  a v a 2  s  .  c om*/
 * ????hacker??license
 * @throws Exception
 */
public static void generateKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyGen.initialize(1024, new SecureRandom());
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    log.info("?");
    DataOutputStream out = new DataOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
    out.writeBytes(EasyUtils.encodeHex(pub.getEncoded()));
    out.close();
    log.info("??" + PUBLIC_KEY_FILE);

    out = new DataOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
    out.writeBytes(EasyUtils.encodeHex(priv.getEncoded()));
    out.close();
    log.info("??" + PRIVATE_KEY_FILE);
}

From source file:com.LaunchKeyManager.http.SimpleMultipartEntity.java

public SimpleMultipartEntity() {
    final StringBuffer buf = new StringBuffer();
    final SecureRandom rand = new SecureRandom();
    for (int i = 0; i < 30; i++) {
        buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
    }//from   ww  w  . jav a 2s.c  om
    this.boundary = buf.toString();

}

From source file:com.baran.file.FileOperator.java

public static String uniqueNameGenerator(String inputFile) {
    // randomization
    SecureRandom random = new SecureRandom();
    BigInteger bi = new BigInteger(130, random);
    String uniqueEncFile = String.valueOf((BigInteger) bi);

    // commons-io-2.4.jar
    String fileNameWithOutExt = FilenameUtils.removeExtension(inputFile);

    String randomFileName = System.getProperty("user.dir") + "\\" + fileNameWithOutExt + "_" + uniqueEncFile
            + ".enc";

    return randomFileName;
}

From source file:org.klnusbaum.udj.network.CustomSSLSocketFactory.java

public CustomSSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(truststore);
    TrustManager[] tm = new TrustManager[] { new FullX509TrustManager() };
    sslContext.init(null, tm, new SecureRandom());
}

From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    PrevSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    PrevHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    proxy = new PokerFace();
    XMLConfiguration conf = new XMLConfiguration();
    conf.load(ProxySpecificTest.class.getResource("/HelloWorldTestConfig.xml"));
    proxy.config(conf);/*from  w w  w . j a  va2s .  c o m*/
    boolean started = proxy.start();
    Assert.assertTrue("Successful proxy start", started);

    SSLContext sc = SSLContext.getInstance("TLS");
    TrustManager[] trustAllCertificates = { new X509TrustAllManager() };
    sc.init(null, trustAllCertificates, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all.
        }
    });

}