RandomString.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.utils;

  21. import java.security.SecureRandom;

  22. /**
  23.  *  RandomString
  24.  *
  25.  * @author Poli Andrea (apoli@link.it)
  26.  * @author $Author$
  27.  * @version $Rev$, $Date$
  28.  */
  29. public class RandomString {

  30.     private static final char[] symbols;

  31.     static {
  32.         StringBuilder tmp = new StringBuilder();
  33.         for (char ch = '0'; ch <= '9'; ++ch)
  34.             tmp.append(ch);
  35.         for (char ch = 'a'; ch <= 'z'; ++ch)
  36.             tmp.append(ch);
  37.         for (char ch = 'A'; ch <= 'Z'; ++ch)
  38.             tmp.append(ch);
  39.         tmp.append("@");
  40.         tmp.append(".");
  41.         symbols = tmp.toString().toCharArray();
  42.     }  

  43.     //private final Random random = new Random();
  44.     private final SecureRandom random = new SecureRandom();

  45.     private final char[] buf;

  46.     public RandomString(int length) {
  47.         if (length < 1)
  48.             throw new IllegalArgumentException("length < 1: " + length);
  49.         this.buf = new char[length];
  50.     }

  51.     public String nextString() {
  52.         for (int idx = 0; idx < this.buf.length; ++idx)
  53.             this.buf[idx] = symbols[this.random.nextInt(symbols.length)];
  54.         return new String(this.buf);
  55.     }
  56. }