Example usage for java.security SecureRandom nextLong

List of usage examples for java.security SecureRandom nextLong

Introduction

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

Prototype

public long nextLong() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

Usage

From source file:pt.aptoide.backupapps.data.webservices.ManagerUploads.java

public static String generateBoundary() {
    try {/*w  w  w .  j a  v  a  2  s .com*/
        // Create a secure random number generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

        // Get 1024 random bits
        byte[] bytes = new byte[1024 / 8];
        sr.nextBytes(bytes);

        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);

        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);

        return "***" + Long.toString(sr.nextLong()) + "***";

    } catch (NoSuchAlgorithmException e) {
    }
    return "*********";
}

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);/*from   w w  w . j  a  v a  2  s. c  o  m*/
    persistCipher();
}

From source file:org.killbill.billing.plugin.payeezy.client.PayeezyClientWrapper.java

private void setHeaders(final String payload, final AsyncHttpClient.BoundRequestBuilder builder) {
    builder.addHeader(APIResourceConstants.SecurityConstants.APIKEY, apiKey);
    builder.addHeader(APIResourceConstants.SecurityConstants.TOKEN, token);
    builder.addHeader(APIResourceConstants.SecurityConstants.APISECRET, secret);

    builder.addHeader("User-Agent", "KillBill 1.0");
    builder.addHeader("Content-Type", "application/json");

    final long nonce;
    try {/*  w w w .  j  a va  2s  .c o m*/
        final SecureRandom sha1PRNG = SecureRandom.getInstance(SHA1_PRNG);
        nonce = Math.abs(sha1PRNG.nextLong());
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    final String nonceString = Long.toString(nonce);
    builder.addHeader(APIResourceConstants.SecurityConstants.NONCE, nonceString);

    final String timestamp = Long.toString(System.currentTimeMillis());
    builder.addHeader(APIResourceConstants.SecurityConstants.TIMESTAMP, timestamp);

    try {
        builder.addHeader(APIResourceConstants.SecurityConstants.AUTHORIZE,
                getMacValue(nonceString, timestamp, payload));
    } catch (final Exception e) {
        logger.warn("Unable to compute HMAC header", e);
    }
}

From source file:org.globusonline.nexus.GlobusOnlineRestClient.java

private long generateNonce() {
    SecureRandom sr = null;
    try {/*w  w w . j a  v a  2  s  .c o m*/
        sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] bytes = new byte[1024 / 8];
        sr.nextBytes(bytes);
        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);
        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return sr.nextLong();
}

From source file:net.bluehornreader.web.ReaderHandler.java

private String getRandomId() {
    SecureRandom secureRandom = new SecureRandom();
    return "" + secureRandom.nextLong();
}

From source file:org.sakaiproject.provider.user.FilterUserDirectoryProvider.java

/**
 * Final initialization, once all dependencies are set.
 *//*w  w  w .  j  av  a 2s  .com*/
public void init() {
    // Initialize the providerID as a random Long. SecureRandom is guaranteed to 
    // to give a separate id, however its not entirely thread safe, so I've reused
    // the thread local. It gets thrown away on the first auth attempt, so the
    // secure random wont hand around in production.

    SecureRandom sr = (SecureRandom) authenticatedProvider.get();
    if (sr == null) {
        sr = new SecureRandom();
        authenticatedProvider.set(sr);
    }
    providerID = new Long(sr.nextLong());
    try {
        m_logger.info("init() FILTER as " + providerID);
    } catch (Throwable t) {
        m_logger.info(".init(): ", t);
    }

}

From source file:net.bluehornreader.web.ReaderHandler.java

private void handleSignupPost(Request request, HttpServletResponse httpServletResponse) throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
        WebUtils.redirectToError("Mismatch between password and password confirmation", request,
                httpServletResponse);//from w w w .j  a  v  a 2 s  . c o  m
        return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
        WebUtils.redirectToError("There already exists a user with the ID " + userId, request,
                httpServletResponse);
        return;
    }

    user = new User(userId, userName, password, salt, email, new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation, false);
    //ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
        StringBuilder bld = new StringBuilder("Invalid values when trying to create user with ID ")
                .append(userId).append("<br/>");
        for (String s : fieldErrors) {
            bld.append(s).append("<br/>");
        }
        WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
        return;
    }

    //ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
}

From source file:net.bluehornreader.web.ReaderHandler.java

private void handleChangePasswordPost(Request request, HttpServletResponse httpServletResponse)
        throws Exception {

    LoginInfo loginInfo = userHelpers.getLoginInfo(request);
    if (loginInfo == null) {
        WebUtils.redirectToError("Couldn't determine the current user", request, httpServletResponse);
        return;//from w  w  w  . j  av a  2s .c  o  m
    }

    String userId = loginInfo.userId;
    String stringCrtPassword = request.getParameter(PARAM_CURRENT_PASSWORD);
    String stringNewPassword = request.getParameter(PARAM_PASSWORD);
    String stringNewPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringNewPassword.equals(stringNewPasswordConfirm)) {
        showResult("Mismatch between password and password confirmation", PATH_SETTINGS, request,
                httpServletResponse);
        return;
    }

    User user = userDb.get(userId); // ttt1 crashes for wrong ID; 2013.07.20 - no longer have an idea what this is about
    if (user == null) {
        WebUtils.redirectToError("Couldn't find the current user", request, httpServletResponse);
        return;
    }

    if (!user.checkPassword(stringCrtPassword)) {
        showResult("Incorrect current password", PATH_SETTINGS, request, httpServletResponse);
        return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringNewPassword, salt);
    user.salt = salt;
    user.password = password;

    //ttt3 2 clients can change the password simultaneously
    userDb.add(user);

    //httpServletResponse.sendRedirect(PATH_SETTINGS);
    showResult("Password changed", PATH_SETTINGS, request, httpServletResponse);
}

From source file:org.springframework.security.config.http.AuthenticationConfigBuilder.java

private String createKey() {
    SecureRandom random = new SecureRandom();
    return Long.toString(random.nextLong());
}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/*from ww w  .  j a v a  2 s .  c o  m*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}