Example usage for java.security SecureRandom nextInt

List of usage examples for java.security SecureRandom nextInt

Introduction

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

Prototype

public int nextInt(int bound) 

Source Link

Document

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Usage

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

private int[] computePaddingLengths(final SecureRandom random) {
    final int firstNumber = random.nextInt(8);// rand 0 through 7
    final int windowAdjustment = 7 - firstNumber;
    final int secondNumber = windowAdjustment + random.nextInt(8 - windowAdjustment);

    if (random.nextBoolean()) {
        return new int[] { firstNumber, secondNumber };
    }/*from  w  w  w .  j  av  a 2 s. c om*/
    return new int[] { secondNumber, firstNumber };
}

From source file:org.iso.mpeg.dash.crypto.ContentProtectionMpegDashSea.java

/**
 * This constructor is used to generate a new instance of baseline content protection
 * TODO clean up this function, 'cause, damn
 * /*  w  ww  .j  a va2  s .co m*/
 * @param contentProtectionNode
 * @throws DashCryptoException
 */
ContentProtectionMpegDashSea(RepresentationType representation, long segmentStartNum)
        throws DashCryptoException {
    super(CONTENT_PROTECTION_SCHEME_ID_URI, segmentStartNum, representation);

    KeySystem baselineKeySys = new KeySystemBaselineHttp(this);
    keySystems.add(baselineKeySys);
    segmentEncryption = new SegmentEncryptionAES128CBC();

    // generate a random key to /tmp/key????????.bin
    SecureRandom secRnd = new SecureRandom();
    String keyPath = "/tmp/key" + Integer.toString(10000000 + secRnd.nextInt(90000000)) + ".bin";
    File keyFile = new File(keyPath);
    if (keyFile.exists())
        throw new DashCryptoException("Error - key file " + keyPath + " already exists");
    byte[] keyBytes = new byte[16];
    secRnd.nextBytes(keyBytes);
    try {
        FileUtils.writeByteArrayToFile(keyFile, keyBytes);
    } catch (IOException e) {
        throw new DashCryptoException(e);
    }

    //      // generate a random IV
    //      byte[] ivBytes = new byte[16];
    //      secRnd.nextBytes(ivBytes);

    // create a single CryptoTimeline, covering all segments, including path to random key and implicit IV      
    int numCryptoPeriods = representation.getSegmentList().getSegmentURLs().size(),
            numSegmentsPerCryptoPeriod = 1;
    if (numCryptoPeriods % 2 == 0) { // if even number of segments, have 2-seg cryptoperiods
        numCryptoPeriods /= 2;
        numSegmentsPerCryptoPeriod *= 2;
    }
    CryptoTimeline cryptoTimeline = new CryptoTimeline(keyPath, this, numCryptoPeriods);
    cryptoTimeline.setNumSegments(numSegmentsPerCryptoPeriod); // one or two segments per cryptoperiod
    //      cryptoTimeline.setIV(ivBytes);
    cryptoPeriods.add(cryptoTimeline);
    preAssignSegmentsToCryptoPeriods();

    // parse internal structure to descriptor (or should we do so lazily?)
    contentProtectionDescriptor = generateContentProtectionDescriptor();
}

From source file:co.rsk.net.discovery.PeerExplorer.java

private Set<Node> collectRandomNodes(List<Node> originalList, int elementsNbr) {
    Set<Node> ret = new HashSet<>();
    SecureRandom rnd = new SecureRandom();
    while (ret.size() < elementsNbr) {
        int i = rnd.nextInt(originalList.size());
        ret.add(originalList.get(i));//from ww  w .  j  av  a2  s.c  o m
    }
    return ret;
}

From source file:com.dbeginc.dbweather.utils.animations.widgets.RainFallView.java

@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
    super.onSizeChanged(width, height, oldWidth, oldHeight);
    SecureRandom random = new SecureRandom();
    Interpolator interpolator = new LinearInterpolator();

    mRainFlakeCount = Math.max(width, height) / 20;
    coords = new int[mRainFlakeCount][];
    drawables.clear();/*from   w  w w. j ava  2  s. c o m*/
    for (int i = 0; i < mRainFlakeCount; i++) {
        Animation animation = new TranslateAnimation(0, height / 10 - random.nextInt(height / 5), 0,
                height + 30);
        animation.setDuration(10 * height + random.nextInt(5 * height));
        animation.setRepeatCount(-1);
        animation.initialize(10, 10, 10, 10);
        animation.setInterpolator(interpolator);

        coords[i] = new int[] { random.nextInt(width - 30), -30 };

        drawables.add(new AnimateDrawable(mRainDrop, animation));
        animation.setStartOffset(random.nextInt(20 * height));
        animation.startNow();
        int y;
        y = random.nextInt(2);
        if (y == 0) {
            drawables.add(new AnimateDrawable(mRainDrop, animation));
        } else {
            drawables.add(new AnimateDrawable(mRainDrop));
        }
    }
}

From source file:com.spotify.sshagenttls.CertHttpsHandler.java

public void handle(final HttpsURLConnection conn) {
    final CertKey certKey;
    try {//www.ja  va 2  s  .  c  o  m
        certKey = createCertKey();
    } catch (IOException | GeneralSecurityException e) {
        if (failOnCertError) {
            throw new RuntimeException(e);
        } else {
            LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. "
                    + "No cert will be sent with request.", getCertSource(), e.toString());
            LOG.debug("full exception fromPaths setting up ClientCertificate follows", e);
            return;
        }
    }

    final Certificate cert = certKey.cert();
    final PrivateKey key = certKey.key();

    // Generate a keystore password.
    // Do all this locally to not make copies of the password in memory.
    final SecureRandom random = new SecureRandom();
    final int numBytes = 60;
    final char[] keyStorePassword = new char[numBytes];
    for (int i = 0; i < numBytes; i++) {
        // Only use ASCII characters for the password. The corresponding integer range is [32, 126].
        keyStorePassword[i] = (char) (random.nextInt(95) + 32);
    }

    try {
        // We're creating a keystore in memory and putting the cert & key into it.
        // The keystore needs a password when we put the key into it, even though it's only going to
        // exist for the lifetime of the process. So we just have some random password that we use.

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", cert);
        keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert });

        // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that
        final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadKeyMaterial(keyStore, keyStorePassword).build();

        // Clear out arrays that had password
        Arrays.fill(keyStorePassword, '\0');

        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException
            | UnrecoverableKeyException | KeyManagementException e) {
        // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more.
        throw new RuntimeException(e);
    }
}

From source file:org.sofun.core.team.WireThemAll.java

@Timeout
// @Schedule(minute = "*/2", hour = "*", persistent = false)
@Lock(LockType.READ)//www.  j a  va 2  s .  c  o  m
public void check() throws Exception {

    if (!available) {
        return;
    } else {
        available = false;
    }

    try {

        List<Member> gambling_members = members.getGamblingMembers();
        for (Member member : gambling_members) {
            float transferrable = members.getTransferableAmountFor(member);
            if (transferrable > 0.1) {
                SecureRandom randomGenerator = new SecureRandom();
                MemberTransaction txn = new MemberTransactionImpl(new Date(), transferrable, CurrencyType.EURO,
                        MemberTransactionType.WIRE_DEBIT);
                txn.setLabel(MemberTransactionType.WIRE_DEBIT);
                txn.setDebit(true);
                txn.setCredit(false);
                txn.setTransactionId(String.valueOf(randomGenerator.nextInt(1000000000)));
                member.addTransaction(txn);
                txn.setMember(member);
                log.info("Wiring amount=" + transferrable + " for member with email=" + member.getEmail());
            }
        }

    } catch (Throwable t) {
        t.printStackTrace();
        log.error(t.getMessage());
    } finally {
        available = true;
    }
}

From source file:org.secuso.privacyfriendlydicegame.MainActivity.java

public int[] rollDice(int poolSize) {

    for (int j = 0; j < 5; j++) {
        backResults[j] = oldResults[j];//w  ww  .  j  a  va2s . c o m
    }

    int[] dice = new int[poolSize];

    for (int i = 0; i < dice.length; i++) {
        if (isLocked[i]) {
            dice[i] = oldResults[i];
        } else {
            SecureRandom random = new SecureRandom();
            byte bytes[] = new byte[6];
            random.nextBytes(bytes);
            dice[i] = random.nextInt(6) + 1;
            oldResults[i] = dice[i];
        }
    }
    return dice;
}

From source file:com.afwsamples.testdpc.SetupManagementFragment.java

@TargetApi(Build.VERSION_CODES.O)
private void passAffiliationIds(Intent intent, PersistableBundle adminExtras) {
    ComponentName admin = DeviceAdminReceiver.getComponentName(getActivity());
    DevicePolicyManager dpm = (DevicePolicyManager) getActivity()
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    List<String> ids = dpm.getAffiliationIds(admin);
    String affiliationId = null;//from  www.  j av a2 s.  c  om
    if (ids.size() == 0) {
        SecureRandom randomGenerator = new SecureRandom();
        affiliationId = Integer.toString(randomGenerator.nextInt(1000000));
        dpm.setAffiliationIds(admin, Arrays.asList(affiliationId));
    } else {
        affiliationId = ids.get(0);
    }
    adminExtras.putString(LaunchIntentUtil.EXTRA_AFFILIATION_ID, affiliationId);
}

From source file:com.autentia.tnt.manager.security.AuthenticationManager.java

/**
 * Generate a new random password//from   ww  w. j  a va 2 s. c om
 * 
 * @return a new random password
 */
private String generateRandomPassword(String[] rnd0, String[] rnd1, String[] rnd2, String[] rnd3,
        String[] rnd4) {
    StringBuilder ret = new StringBuilder();

    // Get lists of random words. We could cache these, but this method is
    // rarely called and caching would
    // depend on user locale, so we prefer to waste CPU better than memory.

    // Get a true random number generator
    SecureRandom rnd;
    try {
        rnd = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException ex) {
        rnd = new SecureRandom();
    }

    // Generate random numbers
    int i0 = rnd.nextInt(rnd0.length);
    int i1 = rnd.nextInt(rnd1.length);
    int i2 = rnd.nextInt(rnd2.length);
    int i3 = rnd.nextInt(rnd3.length);
    int i4 = rnd.nextInt(rnd4.length);

    // Compose password
    ret.append(rnd0[i0]);
    ret.append(rnd1[i1]);
    ret.append(rnd2[i2]);
    ret.append(rnd3[i3]);
    ret.append(rnd4[i4]);

    return ret.toString();
}

From source file:org.pwsafe.passwordsafeswt.dialog.EditDialog.java

private String generatePassword() {
    final String BASE_LETTERS = String.valueOf(PassphraseUtils.LOWERCASE_CHARS);
    final String BASE_DIGITS = String.valueOf(PassphraseUtils.DIGIT_CHARS);
    final String BASE_LETTERS_EASY = "abcdefghjkmnpqrstuvwxyz"; //$NON-NLS-1$
    final String BASE_DIGITS_EASY = "23456789"; //$NON-NLS-1$
    final String BASE_SYMBOLS = "!@#$%^&*()"; //$NON-NLS-1$
    final StringBuilder pwSet = new StringBuilder();

    UserPreferences.reload(); // make sure we have a fresh copy
    final UserPreferences preferenceStore = UserPreferences.getInstance();

    final String passwordLengthStr = preferenceStore.getString(JpwPreferenceConstants.DEFAULT_PASSWORD_LENGTH);
    int passwordLength = 0;
    if (passwordLengthStr != null && passwordLengthStr.trim().length() > 0) {
        passwordLength = Integer.parseInt(passwordLengthStr);
    }/*  w w  w  .j  a va2  s.com*/
    if (passwordLength <= 0)
        passwordLength = 8; // let's be sensible about this..

    final boolean useLowerCase = preferenceStore.getBoolean(JpwPreferenceConstants.USE_LOWERCASE_LETTERS);
    final boolean useUpperCase = preferenceStore.getBoolean(JpwPreferenceConstants.USE_UPPERCASE_LETTERS);
    final boolean useDigits = preferenceStore.getBoolean(JpwPreferenceConstants.USE_DIGITS);
    final boolean useSymbols = preferenceStore.getBoolean(JpwPreferenceConstants.USE_SYMBOLS);
    final boolean useEasyToRead = preferenceStore.getBoolean(JpwPreferenceConstants.USE_EASY_TO_READ);

    if (useLowerCase) {
        if (useEasyToRead) {
            pwSet.append(BASE_LETTERS_EASY.toLowerCase());
        } else {
            pwSet.append(BASE_LETTERS.toLowerCase());
        }
    }

    if (useUpperCase) {
        if (useEasyToRead) {
            pwSet.append(BASE_LETTERS_EASY.toUpperCase());
        } else {
            pwSet.append(BASE_LETTERS.toUpperCase());
        }
    }

    if (useDigits) {
        if (useEasyToRead) {
            pwSet.append(BASE_DIGITS_EASY);
        } else {
            pwSet.append(BASE_DIGITS);
        }
    }

    if (useSymbols) {
        pwSet.append(BASE_SYMBOLS);
    }

    final StringBuffer sb = new StringBuffer();
    if (pwSet.length() > 0) {
        final SecureRandom rand = new SecureRandom();
        rand.setSeed(System.currentTimeMillis());
        for (int i = 0; i < passwordLength; i++) {
            final int randOffset = rand.nextInt(pwSet.length());
            sb.append(pwSet.charAt(randOffset));
        }
    } else {
        sb.append(Messages.getString("EditDialog.MessageMustEditOptions")); //$NON-NLS-1$
    }

    return sb.toString();

}