Example usage for java.security SecureRandom getInstance

List of usage examples for java.security SecureRandom getInstance

Introduction

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

Prototype

public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

Usage

From source file:com.bloatit.framework.utils.Hash.java

public static String generateUniqueToken() {
    UUID.randomUUID().toString();
    try {/*from ww  w . j av a2s .  c om*/
        final byte[] bytes = new byte[RANDOM_SIZE];
        SecureRandom.getInstance(SHA1_PRNG).nextBytes(bytes);
        return DigestUtils.sha512Hex(DigestUtils.sha512Hex(bytes) + UUID.randomUUID().toString());
    } catch (final NoSuchAlgorithmException e) {
        throw new BadProgrammerException(e);
    }
}

From source file:org.cloudfoundry.identity.uaa.login.CachingPasscodeStore.java

public CachingPasscodeStore() {
    try {//from  ww w.ja v  a  2s. co m
        rand = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        // Ignore
    }
}

From source file:edu.internet2.middleware.openid.common.impl.SecureRandomIdentifierGenerator.java

/**
 * Constructor./*from   ww  w .j  a  v a2s.c om*/
 * 
 * @throws NoSuchAlgorithmException thrown if the SHA1PRNG algorithm is not supported by the JVM
 */
public SecureRandomIdentifierGenerator() throws NoSuchAlgorithmException {
    random = SecureRandom.getInstance("SHA1PRNG");
}

From source file:com.qut.middleware.esoemanager.util.PolicyIDGenerator.java

public PolicyIDGenerator() {
    this.lock = new ReentrantLock();

    try {// ww  w . j  a v  a2 s . c om
        /* Attempt to get the specified RNG instance */
        this.random = SecureRandom.getInstance(this.RNG);
    } catch (NoSuchAlgorithmException nsae) {
        this.logger.error(Messages.getString("IdentifierGeneratorImpl.13")); //$NON-NLS-1$
        this.logger.debug(nsae.getLocalizedMessage(), nsae);
        this.random = new SecureRandom();
    }

    this.random.setSeed(System.currentTimeMillis());
}

From source file:com.proctorcam.proctorserv.HashedAuthenticator.java

public static HashMap<String, Object> applyReverseGuidAndSign(HashMap<String, Object> params,
        String customer_identifier, String shared_secret) {
    //Create random GUID
    SecureRandom secRandom = null;
    try {/*from www .  j a v a  2 s  .co  m*/
        secRandom = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException ex) {
        System.err.println(ex.getMessage());
    }
    String guid = new Integer(secRandom.nextInt()).toString();
    params.put("customer_id", customer_identifier);
    params.put("guid", guid);
    params.put("signature", "");

    //Create query string using key-value pairs in params and
    //appending shared_secret
    StringBuilder query = new StringBuilder();

    for (String key : params.keySet()) {
        if (key != "signature") {
            Object data = params.get(key);

            if (is_hashmap(data)) {
                HashMap<String, Object> map = (HashMap<String, Object>) data;
                String hashMapQuery = hashQuery(key, map);
                query.append(hashMapQuery);

            } else if (is_array(data)) {
                Object[] array = getArray(data);
                String arrayString = arrayQuery(key, array);
                query.append(arrayString);

            } else {
                query.append(key).append("=").append(data).append("&");
            }
        }
    }

    //Deletes trailing & from query and append shared_secret
    query.deleteCharAt(query.length() - 1);
    query.append(shared_secret);
    String signature = buildSig(query);

    //Add signature to params
    params.put("signature", signature);

    //Reverse guid in params
    String reverseGUID = new StringBuilder(guid).reverse().toString();
    params.put("guid", reverseGUID);

    return params;
}

From source file:nz.net.orcon.kanban.automation.actions.BulletinAdvancedSmsEndpoint.java

@Override
public String sendMessage(String destination, String message) throws Exception {

    String messageId = RandomStringUtils.random(10, 0, 0, true, true, null,
            SecureRandom.getInstance("SHA1PRNG"));

    if (destination.startsWith("+")) {
        destination = destination.substring(1);
    }/*from   w  w  w . j a v a  2s . c o  m*/

    URL url = new URL(urlName);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    try {
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", encodeBasicAuth(this.user, this.password));
        con.setDoOutput(true);

        StringBuffer form = new StringBuffer();
        form.append("to=").append(destination);

        conditionalAppend(form, "messageId", messageId);
        conditionalAppend(form, "from", this.from);
        conditionalAppend(form, "rateCode", this.rateCode);
        conditionalAppend(form, "body", URLEncoder.encode(message, "UTF-8"));

        //LOGGER.info("Form: " + form.toString());

        OutputStream out = con.getOutputStream();
        try {
            out.write(form.toString().getBytes("US-ASCII"));
        } finally {
            out.close();
        }

        if (!(con.getResponseCode() == 204)) {
            throw new IOException("Return resultcode not success: " + con.getResponseCode());
        }

        return messageId;

    } finally {
        con.disconnect();
    }

}

From source file:com.acc.storefront.security.impl.DefaultGUIDCookieStrategy.java

public DefaultGUIDCookieStrategy() throws NoSuchAlgorithmException {
    random = SecureRandom.getInstance("SHA1PRNG");
    sha = MessageDigest.getInstance("SHA-1");
    Assert.notNull(random);// w  ww.  j a v a 2  s. c  o m
    Assert.notNull(sha);
}

From source file:org.b3log.latke.util.Crypts.java

/**
 * Encrypts by AES./*from   ww w. j a  va2s  . co m*/
 *
 * @param content the specified content to encrypt
 * @param key     the specified key
 * @return encrypted content
 * @see #decryptByAES(java.lang.String, java.lang.String)
 */
public static String encryptByAES(final String content, final String key) {
    try {
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        final SecretKey secretKey = kgen.generateKey();
        final byte[] enCodeFormat = secretKey.getEncoded();
        final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
        final Cipher cipher = Cipher.getInstance("AES");
        final byte[] byteContent = content.getBytes("UTF-8");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        final byte[] result = cipher.doFinal(byteContent);

        return Hex.encodeHexString(result);
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Encrypt failed", e);

        return null;
    }
}

From source file:org.whispersystems.textsecuregcm.auth.AuthenticationCredentials.java

public AuthenticationCredentials(String authenticationToken) {
    try {/*from   w w  w. ja v  a2s  . c o  m*/
        this.salt = Math.abs(SecureRandom.getInstance("SHA1PRNG").nextInt()) + "";
        this.hashedAuthenticationToken = getHashedValue(salt, authenticationToken);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}

From source file:org.standard.bestpratice.security.Secure.java

public void encodeRampartNonce() {
    Random random = null;//from ww w.  j  a  v  a  2 s .  c  o m
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
    } catch (final NoSuchAlgorithmException ex) {
        LOG.error("Sha 1 not find", ex);
    }
    final byte[] r = new byte[16];
    random.nextBytes(r);
    String nonceBase64 = Base64.encodeBase64String(r);

    LOG.debug(r.toString());
    nonceBase64 = nonceBase64.replaceAll("[\r\n]+", "");
    LOG.debug(nonceBase64);
    LOG.debug("saut de ligne");
    //dHxHn8NcEjzaQ4KQX6j27Q==
    //ZlMIni/fEyY4qpBCJXAIxQ==
    //tAzmLb8dbvHtHARq1EF5OQ==
    //0BoFd08zqh1z8htR9WqtrUCayXY=
}