Java Code Examples for java.security.SecureRandom#nextLong()

The following examples show how to use java.security.SecureRandom#nextLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecureRandom.java    From CompetitiveJava with MIT License 6 votes vote down vote up
public static void generateSecureRandomValues() {
    SecureRandom secureRandom = new SecureRandom();

    int randomInt = secureRandom.nextInt();
    long randomLong = secureRandom.nextLong();
    float randomFloat = secureRandom.nextFloat();
    double randomDouble = secureRandom.nextDouble();
    boolean randomBoolean = secureRandom.nextBoolean();

    IntStream randomIntStream = secureRandom.ints();
    LongStream randomLongStream = secureRandom.longs();
    DoubleStream randomDoubleStream = secureRandom.doubles();

    byte[] values = new byte[124];
    secureRandom.nextBytes(values);
}
 
Example 2
Source File: SecureRandomDemo.java    From tutorials with MIT License 6 votes vote down vote up
public static void generateSecureRandomValues() {
    SecureRandom sr = new SecureRandom();

    int randomInt = sr.nextInt();
    long randomLong = sr.nextLong();
    float randomFloat = sr.nextFloat();
    double randomDouble = sr.nextDouble();
    boolean randomBoolean = sr.nextBoolean();

    IntStream randomIntStream = sr.ints();
    LongStream randomLongStream = sr.longs();
    DoubleStream randomDoubleStream = sr.doubles();

    byte[] values = new byte[124];
    sr.nextBytes(values);
}
 
Example 3
Source File: SecureRandomDemo.java    From tutorials with MIT License 6 votes vote down vote up
public static void generateSecureRandomValues() {
    SecureRandom sr = new SecureRandom();

    int randomInt = sr.nextInt();
    long randomLong = sr.nextLong();
    float randomFloat = sr.nextFloat();
    double randomDouble = sr.nextDouble();
    boolean randomBoolean = sr.nextBoolean();

    IntStream randomIntStream = sr.ints();
    LongStream randomLongStream = sr.longs();
    DoubleStream randomDoubleStream = sr.doubles();

    byte[] values = new byte[124];
    sr.nextBytes(values);
}
 
Example 4
Source File: GitTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected IPath createTempDir() throws CoreException {
	// get a temporary folder location, do not use /tmp
	File workspaceRoot = OrionConfiguration.getRootLocation().toLocalFile(EFS.NONE, null);
	File tmpDir = new File(workspaceRoot, SimpleMetaStoreUtil.ARCHIVE);
	if (!tmpDir.exists()) {
		tmpDir.mkdirs();
	}
	if (!tmpDir.exists() || !tmpDir.isDirectory()) {
		fail("Cannot find the default temporary-file directory: " + tmpDir.toString());
	}

	// get a temporary folder name
	SecureRandom random = new SecureRandom();
	long n = random.nextLong();
	n = (n == Long.MIN_VALUE) ? 0 : Math.abs(n);
	String tmpDirStr = Long.toString(n);
	File tempDir = new File(tmpDir, tmpDirStr);
	if (!tempDir.mkdir()) {
		fail("Cannot create a temporary directory at " + tempDir.toString());
	}
	return Path.fromOSString(tempDir.toString());
}
 
Example 5
Source File: RandomDataGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public long nextSecureLong(final long lower, final long upper) throws NumberIsTooLargeException {
    if (lower >= upper) {
        throw new NumberIsTooLargeException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND,
                                            lower, upper, false);
    }
    final long max = (upper - lower) + 1;
    if (max <= 0) {
        // the range is too wide to fit in a positive long (larger than 2^63); as it covers
        // more than half the long range, we use directly a simple rejection method
        final SecureRandom rng = getSecRan();
        while (true) {
            final long r = rng.nextLong();
            if (r >= lower && r <= upper) {
                return r;
            }
        }
    } else if (max < Integer.MAX_VALUE){
        // we can shift the range and generate directly a positive int
        return lower + getSecRan().nextInt((int) max);
    } else {
        // we can shift the range and generate directly a positive long
        return lower + nextLong(getSecRan(), max);
    }
}
 
Example 6
Source File: SyntheticPasswordManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public static long generateHandle() {
    SecureRandom rng = new SecureRandom();
    long result;
    do {
        result = rng.nextLong();
    } while (result == DEFAULT_HANDLE);
    return result;
}
 
Example 7
Source File: BenchmarkExecutor.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static long getSecureIndex() {
  SecureRandom random = new SecureRandom();
  while (true) {
    long nextLong = random.nextLong();
    if (nextLong > 0) {
      return nextLong;
    }
  }
}
 
Example 8
Source File: RestApiKey.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static RestApiKey randomGenerate()
{
    SecureRandom random = new SecureRandom();
    long id = random.nextLong();
    byte[] secret = new byte[32];
    random.nextBytes(secret);
    return new RestApiKey(id, secret);
}
 
Example 9
Source File: SerializableSaltedHasher.java    From CuckooFilter4J with Apache License 2.0 5 votes vote down vote up
static <T> SerializableSaltedHasher<T> create(Algorithm alg, Funnel<? super T> funnel) {
	checkNotNull(alg);
	checkNotNull(funnel);
	SecureRandom randomer = new SecureRandom();
	long seedNSalt = randomer.nextLong();
	long addlSipSeed = randomer.nextLong();
	return new SerializableSaltedHasher<>(seedNSalt, addlSipSeed, funnel, alg);
}
 
Example 10
Source File: MathUtil.java    From cjs_ssms with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 生成正数随机数
 * @param tRandom
 * @return
 */
private static long getAbsRandom(SecureRandom tRandom) {
  long l = tRandom.nextLong();
  if (l == Long.MIN_VALUE) {
    l = Long.MAX_VALUE;
  } else {
    l = Math.abs(l);
  }
  return l;
}
 
Example 11
Source File: EgovDateUtil.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 입력받은 일자 사이의 임의의 일자를 반환
 * @param sDate1 시작일자
 * @param sDate2 종료일자
 * @return 임의일자
 */
public static String getRandomDate(String sDate1, String sDate2) {
	String dateStr1 = validChkDate(sDate1);
	String dateStr2 = validChkDate(sDate2);

	String randomDate = null;

	int sYear, sMonth, sDay;
	int eYear, eMonth, eDay;

	sYear = Integer.parseInt(dateStr1.substring(0, 4));
	sMonth = Integer.parseInt(dateStr1.substring(4, 6));
	sDay = Integer.parseInt(dateStr1.substring(6, 8));

	eYear = Integer.parseInt(dateStr2.substring(0, 4));
	eMonth = Integer.parseInt(dateStr2.substring(4, 6));
	eDay = Integer.parseInt(dateStr2.substring(6, 8));

	GregorianCalendar beginDate = new GregorianCalendar(sYear, sMonth - 1, sDay, 0, 0);
	GregorianCalendar endDate = new GregorianCalendar(eYear, eMonth - 1, eDay, 23, 59);

	if (endDate.getTimeInMillis() < beginDate.getTimeInMillis()) {
		throw new IllegalArgumentException("Invalid input date : " + sDate1 + "~" + sDate2);
	}

	SecureRandom r = new SecureRandom();

	long rand = ((r.nextLong() >>> 1) % (endDate.getTimeInMillis() - beginDate.getTimeInMillis() + 1)) + beginDate.getTimeInMillis();

	GregorianCalendar cal = new GregorianCalendar();
	//SimpleDateFormat calformat = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat calformat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
	cal.setTimeInMillis(rand);
	randomDate = calformat.format(cal.getTime());

	// 랜덤문자열를 리턴
	return randomDate;
}
 
Example 12
Source File: Combat.java    From rogue-cloud with Apache License 2.0 4 votes vote down vote up
public static CombatResult doCombat(IMutableCreature attacker, IMutableCreature defender, LogContext lc) {
		
		SecureRandom sr = new SecureRandom();
		Random r = new Random(sr.nextLong());
		
		Weapon w = attacker.getWeapon();
		
		int totalDefense = defender.getArmour().getAll().stream().mapToInt( (e) -> e.getDefense()).sum();
		
		int damage = 0;
		for(int x = 0; x < w.getNumAttackDice(); x++) {
			
			damage += r.nextInt(w.getAttackDiceSize());
		}
		damage += w.getAttackPlus();
		
		final AtomicReference<Double> damageReduction = new AtomicReference<Double>(1d);
		{
			defender.getActiveEffects().stream().filter(e -> e.getType() == EffectType.DAMAGE_REDUCTION).forEach( e -> {
				damageReduction.set( damageReduction.get() * (1 -  ((double)e.getMagnitude()/100d)   ));
			});
		}
		damage = (int)(damage * damageReduction.get());		
		
//		log.info("Reducing damage by "+(int)(damageReduction.get()*100), lc);
		
		boolean hit = false;
		double hitChance = ((double)w.getHitRating() / (double)totalDefense);
		
		if(r.nextDouble()*1d <= hitChance) {
			hit = true;
			// hit, no damage mitigation
		} else {
			// miss
			damage = 0;
		}
		
		defender.setCurrHp( defender.getHp()- damage);
		
		log.info("Combat: "+attacker.getId()+" -> "+defender.getId()+"(d:"+totalDefense+") = "+(hit ? damage : "MISS")+", now at "+defender.getHp()+" hp", null); 
		
		return new CombatResult(hit, damage);
	}
 
Example 13
Source File: TestCryptoCodec.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Regression test for IV calculation, see HADOOP-11343
 */
@Test(timeout=120000)
public void testCalculateIV() throws Exception {
  JceAesCtrCryptoCodec codec = new JceAesCtrCryptoCodec();
  codec.setConf(conf);

  SecureRandom sr = new SecureRandom();
  byte[] initIV = new byte[16];
  byte[] IV = new byte[16];

  long iterations = 1000;
  long counter = 10000;

  // Overflow test, IV: 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff 
  for(int i = 0; i < 8; i++) {
    initIV[8 + i] = (byte)0xff;
  }

  for(long j = 0; j < counter; j++) {
    assertIVCalculation(codec, initIV, j, IV);
  }

  // Random IV and counter sequence test
  for(long i = 0; i < iterations; i++) {
    sr.nextBytes(initIV);

    for(long j = 0; j < counter; j++) {
      assertIVCalculation(codec, initIV, j, IV);
    }
  }

  // Random IV and random counter test
  for(long i = 0; i < iterations; i++) {
    sr.nextBytes(initIV);

    for(long j = 0; j < counter; j++) {
      long c = sr.nextLong();
      assertIVCalculation(codec, initIV, c, IV);
    }
  }
}
 
Example 14
Source File: Utils.java    From nem.core with MIT License 4 votes vote down vote up
public static Long generateRandomId() {
	final SecureRandom rand = new SecureRandom();
	return rand.nextLong();
}
 
Example 15
Source File: TestCryptoCodec.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Regression test for IV calculation, see HADOOP-11343
 */
@Test(timeout=120000)
public void testCalculateIV() throws Exception {
  JceAesCtrCryptoCodec codec = new JceAesCtrCryptoCodec();
  codec.setConf(conf);

  SecureRandom sr = new SecureRandom();
  byte[] initIV = new byte[16];
  byte[] IV = new byte[16];

  long iterations = 1000;
  long counter = 10000;

  // Overflow test, IV: 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff 
  for(int i = 0; i < 8; i++) {
    initIV[8 + i] = (byte)0xff;
  }

  for(long j = 0; j < counter; j++) {
    assertIVCalculation(codec, initIV, j, IV);
  }

  // Random IV and counter sequence test
  for(long i = 0; i < iterations; i++) {
    sr.nextBytes(initIV);

    for(long j = 0; j < counter; j++) {
      assertIVCalculation(codec, initIV, j, IV);
    }
  }

  // Random IV and random counter test
  for(long i = 0; i < iterations; i++) {
    sr.nextBytes(initIV);

    for(long j = 0; j < counter; j++) {
      long c = sr.nextLong();
      assertIVCalculation(codec, initIV, c, IV);
    }
  }
}
 
Example 16
Source File: Random.java    From quilt with Apache License 2.0 4 votes vote down vote up
private static SecureRandom newDefaultSecureRandom() {
  SecureRandom retval = new SecureRandom();
  retval.nextLong(); // force seeding
  return retval;
}
 
Example 17
Source File: PageDAOTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void testGetPagesByRoleKey( )
{
    SecureRandom rnd = new SecureRandom( );
    Role role = null;
    Page page = null;
    try
    {
        // create a role
        String randomRoleName = "role" + rnd.nextLong( );
        role = new Role( );
        role.setRole( randomRoleName );
        role.setRoleDescription( randomRoleName );
        role.setWorkgroup( AdminWorkgroupService.ALL_GROUPS );
        RoleHome.create( role );
        // create a page
        String randomPageName = "page" + rnd.nextLong( );
        page = new Page( );
        page.setParentPageId( PortalService.getRootPageId( ) );
        page.setPageTemplateId( PageTemplateHome.getPageTemplatesList( ).get( 0 ).getId( ) );
        page.setName( randomPageName );
        page.setRole( randomRoleName );
        page.setDateUpdate( new Timestamp( new java.util.Date( ).getTime( ) ) );
        page.setDisplayDateUpdate( false );
        page.setIsManualDateUpdate( false );
        IPageService pageService = (IPageService) SpringContextService.getBean( "pageService" );
        pageService.createPage( page );
        // get page by role
        PageDAO dao = new PageDAO( );
        Collection<Page> pages = dao.getPagesByRoleKey( randomRoleName );
        assertNotNull( pages );
        for ( Page p : pages )
        {
            if ( p.getName( ).equals( randomPageName ) )
            {
                return;
            }
        }
        Assert.fail( "could not find the page " + randomPageName );
    }
    finally
    {
        // cleanup
        if ( role != null )
        {
            try
            {
                RoleHome.remove( role.getRole( ) );
            }
            finally
            {
            }
        }
        if ( page != null )
        {
            try
            {
                PageHome.remove( page.getId( ) );
            }
            finally
            {
            }
        }
    }

}
 
Example 18
Source File: RemoteBlockStreamHandle.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Generate a random number for use as a block stream authentication token.
 * @return random value
 */
private static synchronized long getRandom() {
	SecureRandom random = SecureRandomFactory.getSecureRandom();
	return random.nextLong();
}
 
Example 19
Source File: Uint128.java    From symja_android_library with GNU General Public License v3.0 4 votes vote down vote up
private static void testPerformance() {
	SecureRandom RNG = new SecureRandom();
	int NCOUNT = 10000000;
	
	// set up test numbers
	long[] a_arr = new long[NCOUNT];
	long[] b_arr = new long[NCOUNT];
	Uint128[] a128_arr =  new Uint128[NCOUNT];
	Uint128[] b128_arr =  new Uint128[NCOUNT];
	
	for (int i=0; i<NCOUNT; i++) {
		a_arr[i] = RNG.nextLong();
		b_arr[i] = RNG.nextLong();
		a128_arr[i] = new Uint128(a_arr[i], RNG.nextLong());
		b128_arr[i] = new Uint128(b_arr[i], RNG.nextLong());
	}
	
	// test performance of add implementations
	long t0 = System.currentTimeMillis();
	for (int i=0; i<NCOUNT; i++) {
		a128_arr[i].add_v1(b128_arr[i]);
	}
	long t1 = System.currentTimeMillis();
	LOG.info("add_v1 took " + (t1-t0) + "ms");

	t0 = System.currentTimeMillis();
	for (int i=0; i<NCOUNT; i++) {
		a128_arr[i].add/*_v2*/(b128_arr[i]);
	}
	t1 = System.currentTimeMillis();
	LOG.info("add_v2 took " + (t1-t0) + "ms");
	// The results of this comparison seem to be misleading. If we compare the two implementations
	// in different PollardRhoBrentMontgomery63 variants than v2 is much faster...
	
	// test performance of mul64 implementations
	t0 = System.currentTimeMillis();
	for (int i=0; i<NCOUNT; i++) {
		mul64_v1(a_arr[i], b_arr[i]);
	}
	t1 = System.currentTimeMillis();
	LOG.info("mul64_v1 took " + (t1-t0) + "ms");
	
	t0 = System.currentTimeMillis();
	for (int i=0; i<NCOUNT; i++) {
		mul64/*_v2*/(a_arr[i], b_arr[i]);
	}
	t1 = System.currentTimeMillis();
	LOG.info("mul64_v2 took " + (t1-t0) + "ms");
}
 
Example 20
Source File: MacAddress.java    From android_9.0.0_r45 with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a generated MAC address whose 46 bits, excluding the locally assigned bit and the
 * unicast bit, are randomly selected.
 *
 * The locally assigned bit is always set to 1. The multicast bit is always set to 0.
 *
 * @return a random locally assigned, unicast MacAddress.
 *
 * @hide
 */
public static @NonNull MacAddress createRandomUnicastAddress() {
    SecureRandom r = new SecureRandom();
    long addr = r.nextLong() & VALID_LONG_MASK;
    addr |= LOCALLY_ASSIGNED_MASK;
    addr &= ~MULTICAST_MASK;
    return new MacAddress(addr);
}