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

The following examples show how to use java.security.SecureRandom#nextInt() . 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: NumberUtil.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
    * 특정숫자 집합에서 랜덤 숫자를 구하는 기능 시작숫자와 종료숫자 사이에서 구한 랜덤 숫자를 반환한다
    *
    * @param startNum - 시작숫자
    * @param endNum - 종료숫자
    * @return 랜덤숫자
    * @exception MyException
    * @see
    */
   public static int getRandomNum(int startNum, int endNum) {
int randomNum = 0;

try {
    // 랜덤 객체 생성
    SecureRandom rnd = new SecureRandom();

    do {
	// 종료숫자내에서 랜덤 숫자를 발생시킨다.
	randomNum = rnd.nextInt(endNum + 1);
    } while (randomNum < startNum); // 랜덤 숫자가 시작숫자보다 작을경우 다시 랜덤숫자를 발생시킨다.
} catch (Exception e) {
    //e.printStackTrace();
    throw new RuntimeException(e);	// 2011.10.10 보안점검 후속조치
}

return randomNum;
   }
 
Example 2
Source File: SimpleAdapter.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
@Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

        TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.stick_text);
        textView.setText(String.valueOf(getItem(position).charAt(0)));
//        viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
        viewHolder.itemView.setBackgroundColor(Color.parseColor("#AAffffff"));
        ImageView imageView = (ImageView) viewHolder.itemView.findViewById(R.id.stick_img);

        SecureRandom imgGen = new SecureRandom();
        switch (imgGen.nextInt(3)) {
            case 0:
                imageView.setImageResource(R.drawable.test_back1);
                break;
            case 1:
                imageView.setImageResource(R.drawable.test_back2);
                break;
            case 2:
                imageView.setImageResource(R.drawable.test_back);
                break;
        }

    }
 
Example 3
Source File: SimpleAdapter.java    From UltimateRecyclerView with Apache License 2.0 6 votes vote down vote up
@Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

        TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.stick_text);
        textView.setText(String.valueOf(getItem(position).charAt(0)));
//        viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
        viewHolder.itemView.setBackgroundColor(Color.parseColor("#AAffffff"));
        ImageView imageView = (ImageView) viewHolder.itemView.findViewById(R.id.stick_img);

        SecureRandom imgGen = new SecureRandom();
        switch (imgGen.nextInt(3)) {
            case 0:
                imageView.setImageResource(R.drawable.jr1);
                break;
            case 1:
                imageView.setImageResource(R.drawable.jr2);
                break;
            case 2:
                imageView.setImageResource(R.drawable.jr3);
                break;
        }

    }
 
Example 4
Source File: GF2Vector.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a random GF2Vector of the given length.
 *
 * @param length the length of the vector
 * @param sr     the source of randomness
 */
public GF2Vector(int length, SecureRandom sr)
{
    this.length = length;

    int size = (length + 31) >> 5;
    v = new int[size];

    // generate random elements
    for (int i = size - 1; i >= 0; i--)
    {
        v[i] = sr.nextInt();
    }

    // erase unused bits
    int r = length & 0x1f;
    if (r != 0)
    {
        // erase unused bits
        v[size - 1] &= (1 << r) - 1;
    }
}
 
Example 5
Source File: AutoReseed.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    SecureRandom sr;
    boolean pass = true;
    for (String mech : new String[]{"Hash_DRBG", "HMAC_DRBG", "CTR_DRBG"}) {
        try {
            System.out.println("Testing " + mech + "...");
            Security.setProperty("securerandom.drbg.config", mech);

            // Check auto reseed works
            sr = SecureRandom.getInstance("DRBG");
            sr.nextInt();
            sr = SecureRandom.getInstance("DRBG");
            sr.reseed();
            sr = SecureRandom.getInstance("DRBG");
            sr.generateSeed(10);
        } catch (Exception e) {
            pass = false;
            e.printStackTrace(System.out);
        }
    }
    if (!pass) {
        throw new RuntimeException("At least one test case failed");
    }
}
 
Example 6
Source File: ARI.java    From ari4java with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates a pseudo-random ID like "a4j.ZH6IA.IXEX0.TUIE8".
 *
 * @return the UID
 */
public static String getUID() {
    StringBuilder sb = new StringBuilder(20);
    sb.append("a4j");
    SecureRandom random = new SecureRandom();
    for (int n = 0; n < 15; n++) {
        if ((n % 5) == 0) {
            sb.append(".");
        }
        int pos = random.nextInt(ALLOWED_IN_UID.length());
        sb.append(ALLOWED_IN_UID.charAt(pos));
    }
    return sb.toString();
}
 
Example 7
Source File: Generator.java    From nbvcxz with MIT License 5 votes vote down vote up
/**
 * Generates a random password of the specified length with the specified characters.
 *
 * @param characterTypes the types of characters to include in the password
 * @param length         the length of the password
 * @return the password
 */
public static String generateRandomPassword(final CharacterTypes characterTypes, final int length)
{
    final StringBuffer buffer = new StringBuffer();
    String characters = "";

    switch (characterTypes)
    {

        case ALPHA:
            characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            break;

        case ALPHANUMERIC:
            characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            break;

        case ALPHANUMERICSYMBOL:
            characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()";
            break;

        case NUMERIC:
            characters = "1234567890";
            break;
    }

    final int charactersLength = characters.length();
    final SecureRandom rnd = new SecureRandom();

    for (int i = 0; i < length; i++)
    {
        final double index = rnd.nextInt(charactersLength);
        buffer.append(characters.charAt((int) index));
    }
    return buffer.toString();
}
 
Example 8
Source File: HelloCookieManager.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
D10HelloCookieManager(SecureRandom secureRandom) {
    this.secureRandom = secureRandom;

    this.cookieVersion = secureRandom.nextInt();
    this.cookieSecret = new byte[32];
    this.legacySecret = new byte[32];

    secureRandom.nextBytes(cookieSecret);
    System.arraycopy(cookieSecret, 0, legacySecret, 0, 32);
}
 
Example 9
Source File: RandomTokenGeneratorImpl.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String generate(int length) {
    StringBuilder token = new StringBuilder();
    SecureRandom random = new SecureRandom();
    for (int i = 0; i < length; i++) {
        int pos = random.nextInt(ALPHABET_LENGTH);
        token.append(ALPHABET[pos]);
    }
    return token.toString();
}
 
Example 10
Source File: DetectSchemaTest.java    From systemds with Apache License 2.0 5 votes vote down vote up
private static String[] doubleSpecialData(int rows) {
	String[] dataArray = new String[]{"Infinity", "3.4028234e+38", "Nan" , "-3.4028236e+38" };
	String[] A = new String[rows];
	SecureRandom random = new SecureRandom();
	for (int j = 0; j < rows; j++)
		A[j] = dataArray[random.nextInt(4)];
	return A;
}
 
Example 11
Source File: CryptoHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static String pronounceable(SecureRandom random) {
    final int rand = random.nextInt(4);
    char[] output = new char[rand * 2 + (5 - rand)];
    boolean vowel = random.nextBoolean();
    for (int i = 0; i < output.length; ++i) {
        output[i] = vowel ? VOWELS[random.nextInt(VOWELS.length)] : CONSONANTS[random.nextInt(CONSONANTS.length)];
        vowel = !vowel;
    }
    return String.valueOf(output);
}
 
Example 12
Source File: GF2Matrix.java    From ripple-lib-java with ISC License 5 votes vote down vote up
/**
 * Create a nxn random upper triangular matrix.
 *
 * @param n  number of rows (and columns)
 * @param sr source of randomness
 */
private void assignRandomUpperTriangularMatrix(int n, SecureRandom sr)
{
    numRows = n;
    numColumns = n;
    length = (n + 31) >>> 5;
    matrix = new int[numRows][length];
    int rest = n & 0x1f;
    int help;
    if (rest == 0)
    {
        help = 0xffffffff;
    }
    else
    {
        help = (1 << rest) - 1;
    }
    for (int i = 0; i < numRows; i++)
    {
        int q = i >>> 5;
        int r = i & 0x1f;
        int s = r;
        r = 1 << r;
        for (int j = 0; j < q; j++)
        {
            matrix[i][j] = 0;
        }
        matrix[i][q] = (sr.nextInt() << s) | r;
        for (int j = q + 1; j < length; j++)
        {
            matrix[i][j] = sr.nextInt();
        }
        matrix[i][length - 1] &= help;
    }

}
 
Example 13
Source File: Graph.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
public boolean addSignature(String nonce){
	try{
		SecureRandom secureRandom = new SecureRandom();
		secureRandom.nextInt();
		Signature signature = Signature.getInstance("SHA256withRSA");
		PrivateKey privateKey = Kernel.getServerPrivateKey("serverprivate");
		if(privateKey == null){
			return false;
		}
		signature.initSign(privateKey, secureRandom);

		for(AbstractVertex vertex : vertexSet()){
			signature.update(vertex.bigHashCodeBytes());
		}
		for(AbstractEdge edge : edgeSet()){
			signature.update(edge.bigHashCodeBytes());
		}
		if(getQueryString() != null){
			signature.update(getQueryString().getBytes("UTF-8"));
		}
		if(nonce != null){
			signature.update(nonce.getBytes("UTF-8"));
		}

		byte[] digitalSignature = signature.sign();
		setSignature(digitalSignature);

		return true;
	}catch(Exception ex){
		logger.log(Level.SEVERE, "Error signing the result graph!", ex);
	}
	return false;
}
 
Example 14
Source File: TlsBlockCipher.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected int chooseExtraPadBlocks(SecureRandom r, int max)
{
    // return r.nextInt(max + 1);

    int x = r.nextInt();
    int n = lowestBitSet(x);
    return Math.min(n, max);
}
 
Example 15
Source File: TablesEncryptor.java    From OpenRS with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	try (Cache cache = new Cache(FileStore.open(Constants.CACHE_PATH))) {
		for (int type = 0; type < cache.getTypeCount(); type++) {
			ByteBuffer buf = cache.getStore().read(255, type);
			if (buf != null && buf.limit() > 0) {
				BufferedWriter writer = new BufferedWriter(new FileWriter(new File(Constants.XTABLE_PATH, type + ".txt")));
				SecureRandom random = new SecureRandom();
				int[] keys = new int[4];
				for (int i = 0; i < keys.length; i++) {
					keys[i] = random.nextInt();
					
					writer.write(String.valueOf(keys[i]));
					writer.newLine();
				}
				writer.flush();
				writer.close();
				
				Container container = Container.decode(buf);
				ByteBuffer buffer = container.encode(keys);
				cache.getStore().write(255, type, buffer);
			}
		}
		
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: SwirldsAdaptor.java    From exo-demo with MIT License 5 votes vote down vote up
private void setupSecuredSocket() {		
	ClientConfig config = ExoConfig.getConfig().clientConfig;
	
	try {
		SecureRandom secureRandom = new SecureRandom();
		secureRandom.nextInt();
		
		KeyStore clientKeyStore = KeyStore.getInstance("JKS");
		clientKeyStore.load(new FileInputStream(config.clientKeystore.path), config.clientKeystore.password.toCharArray());
		
		KeyStore serverKeyStore = KeyStore.getInstance("JKS");
		serverKeyStore.load(new FileInputStream(config.serverKeystore.path), config.serverKeystore.password.toCharArray());
		
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		tmf.init(serverKeyStore);
		
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(clientKeyStore, "client".toCharArray());
		
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom);
		
		SSLSocketFactory socketFactory = sslContext.getSocketFactory();
		InetSocketAddress destination = (InetSocketAddress) SwirldsAdaptor.nodeRouter.getNode();

		System.out.println("Attempting to create a connection to " + destination.getHostName() + ":" + destination.getPort());
		this.socket = socketFactory.createSocket(destination.getHostName(), destination.getPort());  //new Socket(HOST, PORT);
	} catch (	IOException | 
				KeyStoreException | 
				NoSuchAlgorithmException | 
				CertificateException | 
				UnrecoverableKeyException | 
				KeyManagementException e) {
		e.printStackTrace();
		throw new IllegalStateException("An error has occurred while configuring a secured socket:  " + e.getMessage());
	}
}
 
Example 17
Source File: CordovaBridge.java    From lona with GNU General Public License v3.0 5 votes vote down vote up
/** Called by cordova.js to initialize the bridge. */
//On old Androids SecureRandom isn't really secure, this is the least of your problems if
//you're running Android 4.3 and below in 2017
@SuppressLint("TrulyRandom")
int generateBridgeSecret() {
    SecureRandom randGen = new SecureRandom();
    expectedBridgeSecret = randGen.nextInt(Integer.MAX_VALUE);
    return expectedBridgeSecret;
}
 
Example 18
Source File: GenericStringObfuscator.java    From genesis with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a random string based on the dictionary
 * <code>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</code>. The
 * length of the string is equal to at least 10 characters, with a maximum
 * of the given length (<code>lengthIndication</code>) plus 10.
 *
 * @param lengthIndication the length that is roughly requested. The
 * returned string is maximally 15 characters longer
 * @return a random string which is equal to at least 10 and maximally equal
 * to the value of <code>lengthIndication</code> plus 10.
 */
public String generateRandomString(int lengthIndication) {
    /**
     * Ensure that no negative value is used. If this is the case, simply
     * set the value to zero, since the additional 10 random characters that
     * are generated will suffice in this case
     */
    if (lengthIndication < 0) {
        lengthIndication = 0;
    }
    //Create the dictionary variable
    String dictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //Create the output variable
    String output = "";
    //Create a new secure random object
    SecureRandom random = new SecureRandom();
    //Get the length, with 10 as a minimum value
    int length = random.nextInt(lengthIndication) + 10;
    //Iterate for the given length
    for (int i = 0; i < length; i++) {
        //Get a random value that is within the bounds of the given dictionary
        int randomValue = random.nextInt(dictionary.length());
        //Append the character from the dictionary to the output
        output += dictionary.substring(randomValue, randomValue + 1);
    }
    //Return the output
    return output;
}
 
Example 19
Source File: RandomNumbersGenerator.java    From tutorials with MIT License 4 votes vote down vote up
public Integer generateRandomWithSecureRandomWithinARange(int min, int max) {
    SecureRandom secureRandom = new SecureRandom();
    int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min;
    return randomWithSecureRandomWithinARange;
}
 
Example 20
Source File: CordovaBridge.java    From chappiecast with Mozilla Public License 2.0 4 votes vote down vote up
/** Called by cordova.js to initialize the bridge. */
int generateBridgeSecret() {
    SecureRandom randGen = new SecureRandom();
    expectedBridgeSecret = randGen.nextInt(Integer.MAX_VALUE);
    return expectedBridgeSecret;
}