¿Cómo generar una cadena alfanumérica aleatoria?


He estado buscando un simple algoritmo Java para generar una cadena alfanumérica pseudoaleatoria. En mi situación, se usaría como un identificador de sesión / clave único que "probablemente" sería único en más de 500K generación (mis necesidades realmente no requieren nada mucho más sofisticado). Idealmente, sería capaz de especificar una longitud dependiendo de mis necesidades de singularidad. Por ejemplo, una cadena generada de longitud 12 podría tener un aspecto similar a "AEYGF7K0DM1X".

Author: Todd, 2008-09-03

30 answers

Algoritmo

Para generar una cadena aleatoria, concatene caracteres extraídos aleatoriamente del conjunto de símbolos aceptables hasta que la cadena alcance la longitud deseada.

Aplicación

Aquí hay un código bastante simple y muy flexible para generar identificadores aleatorios. Lea la información que sigue para ver las notas de aplicación importantes.

import java.security.SecureRandom;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;

public class RandomString {

    /**
     * Generate a random string.
     */
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];
    }

    /**
     * Create an alphanumeric string generator.
     */
    public RandomString(int length, Random random) {
        this(length, random, alphanum);
    }

    /**
     * Create an alphanumeric strings from a secure generator.
     */
    public RandomString(int length) {
        this(length, new SecureRandom());
    }

    /**
     * Create session identifiers.
     */
    public RandomString() {
        this(21);
    }

}

Ejemplos de uso

Crear un generador inseguro para 8 caracteres identificadores:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Crear un generador seguro para identificadores de sesión:

RandomString session = new RandomString();

Cree un generador con códigos fáciles de leer para imprimir. Las cadenas son más largas que las cadenas alfanuméricas completas para compensar el uso de menos símbolos:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Utilizar como identificadores de sesión

Generar identificadores de sesión que probablemente sean únicos no es suficiente, o simplemente podría usar un contador simple. Los atacantes secuestran sesiones cuando identificadores predecibles son utilizar.

Hay tensión entre la longitud y la seguridad. Los identificadores más cortos son más fáciles de adivinar, porque hay menos posibilidades. Pero los identificadores más largos consumen más almacenamiento y ancho de banda. Un conjunto más grande de símbolos ayuda, pero puede causar problemas de codificación si los identificadores se incluyen en las URL o se vuelven a introducir a mano.

La fuente subyacente de aleatoriedad, o entropía, para los identificadores de sesión debe provenir de un generador de números aleatorios diseñado para criptografía. Obstante, la inicialización de estos generadores a veces puede ser computacionalmente costosa o lenta, por lo que se debe hacer un esfuerzo para reutilizarlos cuando sea posible.

Utilizar como identificadores de objetos

No todas las aplicaciones requieren seguridad. La asignación aleatoria puede ser una forma eficiente para que varias entidades generen identificadores en un espacio compartido sin ninguna coordinación o partición. La coordinación puede ser lenta, especialmente en un entorno agrupado o distribuido, y dividir un espacio causa problemas cuando las entidades terminan con acciones que son demasiado pequeñas o demasiado grandes.

Los identificadores generados sin tomar medidas para hacerlos impredecibles deben protegerse por otros medios si un atacante puede verlos y manipularlos, como sucede en la mayoría de las aplicaciones web. Debe haber un sistema de autorización separado que proteja los objetos cuyo identificador pueda ser adivinado por un atacante sin permiso de acceso.

También se debe tener cuidado de usar identificadores que sean largos suficiente para que las colisiones sean improbables dado el número total previsto de identificadores. Esto se conoce como " la paradoja del cumpleaños." La probabilidad de una colisión, p , es aproximadamente n2/(2qx ), donde n es el número de identificadores realmente generados, q es el número de símbolos distintos en el alfabeto, y x es la longitud de los identificadores. Este debe ser un número muy pequeño, como 2-50 o menos.

Trabajando esto muestra que la posibilidad de colisión entre 500k identificadores de 15 caracteres es de aproximadamente 2-52, lo cual es probablemente menos probable que errores no detectados de rayos cósmicos, etc.

Comparación con UUID

De acuerdo con sus especificaciones, los UUID no están diseñados para ser impredecibles, y no deben usarse como identificadores de sesión.

Los UUID en su formato estándar ocupan mucho espacio: 36 caracteres para solo 122 bits de entropía. (No todos los bits de un UUID "aleatorio" se seleccionan aleatoriamente.) Una cadena alfanumérica elegida al azar contiene más entropía en solo 21 caracteres.

Los UUID no son flexibles; tienen una estructura y un diseño estandarizados. Esta es su principal virtud, así como su principal debilidad. Al colaborar con una parte externa, la estandarización ofrecida por UUIDs puede ser útil. Para uso puramente interno, pueden ser ineficientes.

 1416
Author: erickson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 23:34:53

Java proporciona una forma de hacer esto directamente. Si no quieres los guiones, son fáciles de quitar. Solo use uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {
        System.out.println(generateString());
    }

    public static String generateString() {
        String uuid = UUID.randomUUID().toString();
        return "uuid = " + uuid;
    }
}

Salida:

uuid = 2d7428a6-b58c-4008-8575-f05549f16316
 746
Author: Steve McLeod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-30 06:09:52
static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static SecureRandom rnd = new SecureRandom();

String randomString( int len ){
   StringBuilder sb = new StringBuilder( len );
   for( int i = 0; i < len; i++ ) 
      sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
   return sb.toString();
}
 474
Author: maxp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-25 10:41:59

Si estás feliz de usar clases de Apache, puedes usar org.apache.commons.text.RandomStringGenerator (commons-text).

Ejemplo:

RandomStringGenerator randomStringGenerator =
        new RandomStringGenerator.Builder()
                .withinRange('0', 'z')
                .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
                .build();
randomStringGenerator.generate(12); // toUpperCase() if you want

Desde commons-lang 3.6, RandomStringUtils está obsoleto.

 457
Author: numéro6,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-18 07:58:04

En una línea:

Long.toHexString(Double.doubleToLongBits(Math.random()));

Http://mynotes.wordpress.com/2009/07/23/java-generating-random-string /

 94
Author: 3 revs, 3 users 71%anonymous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-29 02:29:50

Puede usar la biblioteca Apache para esto: RandomStringUtils

RandomStringUtils.randomAlphanumeric(20).toUpperCase();
 89
Author: manish_s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-09 14:15:43

Usar Dollar debe ser simple como:

// "0123456789" + "ABCDE...Z"
String validCharacters = $('0', '9').join() + $('A', 'Z').join();

String randomString(int length) {
    return $(validCharacters).shuffle().slice(length).toString();
}

@Test
public void buildFiveRandomStrings() {
    for (int i : $(5)) {
        System.out.println(randomString(12));
    }
}

Produce algo así:

DKL1SBH9UJWC
JH7P0IT21EA5
5DTI72EO6SFU
HQUMJTEBNF7Y
1HCR6SKYWGT7
 38
Author: dfa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-29 02:30:13

Esto es fácilmente alcanzable sin ninguna librería externa.

1. Generación de Datos Pseudoaleatorios Criptográficos

Primero necesita un PRNG criptográfico. Java tiene SecureRandom para ello utiliza normalmente la mejor fuente de entropía de la máquina (por ejemplo, /dev/random). Lea más aquí.

SecureRandom rnd = new SecureRandom();
byte[] token = new byte[byteLength];
rnd.nextBytes(token);

Nota: SecureRandom es la forma más lenta, pero más segura en Java de generar bytes aleatorios. Sin embargo, recomiendo NO considerar el rendimiento aquí ya que por lo general, no tiene un impacto real en su aplicación a menos que tenga que generar millones de tokens por segundo.

2. Espacio Requerido de Posibles Valores

A continuación tienes que decidir "qué tan único" debe ser tu token. El único punto de considerar la entropía es asegurarse de que el sistema pueda resistir ataques de fuerza bruta: el espacio de valores posibles debe ser tan grande que cualquier atacante solo podría intentar una proporción insignificante de los valores en no-ridicrous tiempo1. Identificadores únicos como random UUID tener 122bit de entropía (es decir. 2^122 = 5. 3x10^36) - la posibilidad de colisión es" *(...) para que haya una posibilidad de duplicación de uno en mil millones, se deben generar 103 billones de UUID versión 42". Elegiremos 128 bits ya que encaja exactamente en 16 bytes y se ve como altamente suficiente para ser único para básicamente todos, pero los más extremos, casos de uso y no tengo que pensar en duplicados. Aquí hay una tabla de comparación simple de entropía que incluye un análisis simple del problema de cumpleaños .

comparación de tamaños de token

Para requisitos simples, la longitud de 8 o 12 bytes podría ser suficiente, pero con 16 bytes está en el "lado seguro".

Y eso es básicamente todo. Lo último es pensar en la codificación para que pueda representarse como un texto imprimible (read, a String).

3. Binario a Texto Codificación

Las codificaciones típicas incluyen:

  • Base64 cada personaje codifica 6 bits creando una sobrecarga del 33%. Desafortunadamente no hay una implementación estándar en el JDK ( 7 y por debajo de - hay en Android y Java 8+). Pero existen numerosas bibliotecas que añaden esto. La desventaja es que el estándar Base64 no es seguro para eg. url y como nombre de archivo en la mayoría de los sistemas de archivos que requieren codificación adicional (por ejemplo, url encoding ) o la url versión segura de Base64 se utiliza. Ejemplo codificación de 16 bytes con relleno: XfJhfv3C0P6ag7y9VQxSbw==

  • Base32 cada personaje codifica 5 bits creando una sobrecarga del 40%. Esto usará A-Z y 2-7 haciendo que sea razonablemente eficiente en espacio mientras que es alfanumérico insensible a mayúsculas y minúsculas. No hay una implementación estándar en el JDK. Ejemplo codificación de 16 bytes sin relleno: WUPIL5DQTZGMF4D3NX5L7LNFOY

  • Base16 (hex) cada el carácter codifica 4bit requiriendo 2 caracteres por byte (ie. 16 bytes crear una cadena de longitud 32). Por lo tanto, hex es menos eficiente en espacio que Base32 pero es seguro de usar en la mayoría de los casos (url) ya que solo usa 0-9 y A a F. Ejemplo de codificación de 16 bytes: 4fa3dd0f57cb3bf331441ed285b27735. Vea una discusión SO sobre la conversión a hexadecimal aquí.

Codificaciones adicionales como Base85 y el exótico Base122 existen con mejor/peor eficiencia espacial. Puede crear su propia codificación (que básicamente la mayoría de las respuestas en este hilo lo hacen) pero yo aconsejaría en contra de ella, si usted no tiene requisitos muy específicos. Ver más esquemas de codificación en el artículo de Wikipedia.

4. Resumen y Ejemplo

  • Uso SecureRandom
  • Utilice al menos 16 bytes (2^128) de valores posibles
  • Codifique de acuerdo con sus requisitos (generalmente hex o base32 si lo necesita alfanumérico)

No

  • ... use su codificación home brew: mejor mantenible y legible para otros si ven qué codificación estándar usa en lugar de weird for loops creando caracteres a la vez.
  • ... use UUID: está desperdiciando 6 bits de entropía y tiene una representación de cadena detallada

Ejemplo: Generador de tokens Hexadecimales

public static String generateRandomHexToken(int byteLength) {
    SecureRandom secureRandom = new SecureRandom();
    byte[] token = new byte[byteLength];
    secureRandom.nextBytes(token);
    return new BigInteger(1, token).toString(16); //hex encoding
}

//generateRandomHexToken(16) -> 2189df7475e96aa3982dbeab266497cd

Ejemplo: Herramienta

Si desea una lista para usar herramienta cli puede usar dados: https://github.com/patrickfav/dice

 34
Author: for3st,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-22 14:39:29

Sorprendente que nadie aquí lo haya sugerido pero:

import java.util.UUID

UUID.randomUUID().toString();

Fácil.

El beneficio de esto es que los UUIDs son agradables y largos y están garantizados para ser casi imposibles de colisionar.

Wikipedia tiene una buena explicación de ello:

" ...solo después de generar 1 mil millones de UUID cada segundo durante los próximos 100 años, la probabilidad de crear solo un duplicado sería de aproximadamente 50%."

Http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates

Los primeros 4 bits son el tipo de versión y 2 para la variante, por lo que obtiene 122 bits aleatorios. Así que si quiere puede truncar desde el final para reducir el tamaño del UUID. No se recomienda, pero todavía tiene un montón de aleatoriedad, suficiente para sus registros de 500k fácil.

 29
Author: Michael Allen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-16 11:49:00

Aquí está en Java:

import static java.lang.Math.round;
import static java.lang.Math.random;
import static java.lang.Math.pow;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static org.apache.commons.lang.StringUtils.leftPad

public class RandomAlphaNum {
  public static String gen(int length) {
    StringBuffer sb = new StringBuffer();
    for (int i = length; i > 0; i -= 12) {
      int n = min(12, abs(i));
      sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
    }
    return sb.toString();
  }
}

Aquí hay una ejecución de ejemplo:

scala> RandomAlphaNum.gen(42)
res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
 28
Author: Apocalisp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-03 17:16:38

Una solución corta y fácil, pero utiliza solo minúsculas y numéricas:

Random r = new java.util.Random ();
String s = Long.toString (r.nextLong () & Long.MAX_VALUE, 36);

El tamaño es de aproximadamente 12 dígitos a la base 36 y no se puede mejorar más, de esa manera. Por supuesto, puede agregar varias instancias.

 22
Author: user unknown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 23:29:20

Una alternativa en Java 8 es:

static final Random random = new Random(); // Or SecureRandom
static final int startChar = (int) '!';
static final int endChar = (int) '~';

static String randomString(final int maxLength) {
  final int length = random.nextInt(maxLength + 1);
  return random.ints(length, startChar, endChar + 1)
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
}
 12
Author: Howard Lovatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-03 19:09:43
public static String generateSessionKey(int length){
String alphabet = 
        new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //9
int n = alphabet.length(); //10

String result = new String(); 
Random r = new Random(); //11

for (int i=0; i<length; i++) //12
    result = result + alphabet.charAt(r.nextInt(n)); //13

return result;
}
 8
Author: rina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-09 04:47:13

Usar UUID es inseguro, porque partes del UUID no son aleatorias en absoluto. El procedimiento de @erickson es muy limpio, pero no crea cadenas de la misma longitud. El siguiente fragmento debería ser suficiente:

/*
 * The random generator used by this class to create random keys.
 * In a holder class to defer initialization until needed.
 */
private static class RandomHolder {
    static final Random random = new SecureRandom();
    public static String randomKey(int length) {
        return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)
            .toString(32)).replace('\u0020', '0');
    }
}

¿por Qué elegir length*5. Supongamos el caso simple de una cadena aleatoria de longitud 1, por lo que un carácter aleatorio. Para obtener un carácter aleatorio que contenga todos los dígitos 0-9 y los caracteres a-z, necesitaríamos un número aleatorio entre 0 y 35 para obtener uno de cada carácter. BigInteger proporciona un constructor para generar un número aleatorio, uniformemente distribuido sobre el rango 0 to (2^numBits - 1). Desafortunadamente 35 no es un número que puede ser recibido por 2^numBits-1. Así que tenemos dos opciones: O ir con 2^5-1=31 o 2^6-1=63. Si escogiéramos 2^6 obtendríamos muchos números "unnecesarry" / "longer". Por lo tanto 2^5 es la mejor opción, incluso si perdemos 4 caracteres (w-z). Para generar ahora una cadena de cierta longitud, podemos simplemente usar un número 2^(length*numBits)-1. El último problema, si queremos una cadena con una cierta longitud, random podría generar un número pequeño, por lo que la longitud no se cumple, por lo que tenemos que rellenar la cadena a su longitud requerida anteponiendo ceros.

 8
Author: Kristian Kraljic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 10:56:42
import java.util.Random;

public class passGen{
    //Verison 1.0
    private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
    private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String sChar = "!@#$%^&*";
    private static final String intChar = "0123456789";
    private static Random r = new Random();
    private static String pass = "";

    public static void main (String[] args) {
        System.out.println ("Generating pass...");
        while (pass.length () != 16){
            int rPick = r.nextInt(4);
            if (rPick == 0){
                int spot = r.nextInt(25);
                pass += dCase.charAt(spot);
            } else if (rPick == 1) {
                int spot = r.nextInt (25);
                pass += uCase.charAt(spot);
            } else if (rPick == 2) {
                int spot = r.nextInt (7);
                pass += sChar.charAt(spot);
            } else if (rPick == 3){
                int spot = r.nextInt (9);
                pass += intChar.charAt (spot);
            }
        }
        System.out.println ("Generated Pass: " + pass);
    }
}

Así que lo que esto hace es simplemente agregar la contraseña en la cadena y ... sí, funciona bien... muy simple. Lo escribí

 7
Author: cmpbah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-17 09:42:20

Encontré esta solución que genera una cadena codificada hexadecimal aleatoria. La prueba unitaria proporcionada parece sostener mi caso de uso principal. Aunque, es un poco más complejo que algunas de las otras respuestas proporcionadas.

/**
 * Generate a random hex encoded string token of the specified length
 *  
 * @param length
 * @return random hex string
 */
public static synchronized String generateUniqueToken(Integer length){ 
    byte random[] = new byte[length];
    Random randomGenerator = new Random();
    StringBuffer buffer = new StringBuffer();

    randomGenerator.nextBytes(random);

    for (int j = 0; j < random.length; j++) {
        byte b1 = (byte) ((random[j] & 0xf0) >> 4);
        byte b2 = (byte) (random[j] & 0x0f);
        if (b1 < 10)
            buffer.append((char) ('0' + b1));
        else
            buffer.append((char) ('A' + (b1 - 10)));
        if (b2 < 10)
            buffer.append((char) ('0' + b2));
        else
            buffer.append((char) ('A' + (b2 - 10)));
    }
    return (buffer.toString());
}

@Test
public void testGenerateUniqueToken(){
    Set set = new HashSet();
    String token = null;
    int size = 16;

    /* Seems like we should be able to generate 500K tokens 
     * without a duplicate 
     */
    for (int i=0; i<500000; i++){
        token = Utility.generateUniqueToken(size);

        if (token.length() != size * 2){
            fail("Incorrect length");
        } else if (set.contains(token)) {
            fail("Duplicate token generated");
        } else{
            set.add(token);
        }
    }
}
 5
Author: Todd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 06:49:20
import java.util.Date;
import java.util.Random;

public class RandomGenerator {

  private static Random random = new Random((new Date()).getTime());

    public static String generateRandomString(int length) {
      char[] values = {'a','b','c','d','e','f','g','h','i','j',
               'k','l','m','n','o','p','q','r','s','t',
               'u','v','w','x','y','z','0','1','2','3',
               '4','5','6','7','8','9'};

      String out = "";

      for (int i=0;i<length;i++) {
          int idx=random.nextInt(values.length);
          out += values[idx];
      }
      return out;
    }
}
 5
Author: Jameskittu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 06:50:34
  1. Cambie los caracteres de cadena según sus requisitos.

  2. La cadena es inmutable. Aquí StringBuilder.append es más eficiente que la concatenación de cadenas.


public static String getRandomString(int length) {
       final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
       StringBuilder result = new StringBuilder();
       while(length > 0) {
           Random rand = new Random();
           result.append(characters.charAt(rand.nextInt(characters.length())));
           length--;
       }
       return result.toString();
    }
 5
Author: frisky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-31 17:14:09
import java.util.*;
import javax.swing.*;
public class alphanumeric{
    public static void main(String args[]){
        String nval,lenval;
        int n,len;

        nval=JOptionPane.showInputDialog("Enter number of codes you require : ");
        n=Integer.parseInt(nval);

        lenval=JOptionPane.showInputDialog("Enter code length you require : ");
        len=Integer.parseInt(lenval);

        find(n,len);

    }
    public static void find(int n,int length) {
        String str1="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder sb=new StringBuilder(length);
        Random r = new Random();

        System.out.println("\n\t Unique codes are \n\n");
        for(int i=0;i<n;i++){
            for(int j=0;j<length;j++){
                sb.append(str1.charAt(r.nextInt(str1.length())));
            }
            System.out.println("  "+sb.toString());
            sb.delete(0,length);
        }
    }
}
 4
Author: Suganya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 06:51:18

Realmente no me gusta ninguna de estas respuestas con respecto a la solución "simple": S

Elegiría un simple;), java puro, un liner (la entropía se basa en la longitud de cadena aleatoria y el conjunto de caracteres dado):

public String randomString(int length, String characterSet) {
    return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
}

@Test
public void buildFiveRandomStrings() {
    for (int q = 0; q < 5; q++) {
        System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"));//charachterSet can basically be anything
    }
}

O (un poco más legible antigua manera)

public String randomString(int length, String characterSet) {
    StringBuilder sb = new StringBuilder(); //consider using StringBuffer if needed
    for (int i = 0; i < length; i++) {
        int randomInt = new SecureRandom().nextInt(characterSet.length());
        sb.append(characterSet.substring(randomInt, randomInt + 1));
    }
    return sb.toString();
}

@Test
public void buildFiveRandomStrings() {
    for (int q = 0; q < 5; q++) {
        System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); //charachterSet can basically be anything
    }
}

Pero por otro lado también podría ir con UUID que tiene una entropía bastante buena ( https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions):

UUID.randomUUID().toString().replace("-", "")

Espero que eso ayude.

 4
Author: Patrik Bego,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 15:55:12

Aquí está una solución de Scala:

(for (i <- 0 until rnd.nextInt(64)) yield { 
  ('0' + rnd.nextInt(64)).asInstanceOf[Char] 
}) mkString("")
 3
Author: Ugo Matrangolo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-24 11:11:01

Puede usar la clase UUID con su mensaje getLeastSignificantBits() para obtener 64 bits de datos aleatorios, luego convertirlo a un número radix 36 (es decir,una cadena que consta de 0-9, A-Z):

Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));

Esto produce una cadena de hasta 13 caracteres. Usamos Matemáticas.abs() para asegurarse de que no hay un signo menos colándose.

 3
Author: neuhaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-29 14:07:23

Puede utilizar el siguiente código, si su contraseña obligatoria contiene números caracteres especiales alfabéticos:

private static final String NUMBERS = "0123456789";
private static final String UPPER_ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWER_ALPHABETS = "abcdefghijklmnopqrstuvwxyz";
private static final String SPECIALCHARACTERS = "@#$%&*";
private static final int MINLENGTHOFPASSWORD = 8;

public static String getRandomPassword() {
    StringBuilder password = new StringBuilder();
    int j = 0;
    for (int i = 0; i < MINLENGTHOFPASSWORD; i++) {
        password.append(getRandomPasswordCharacters(j));
        j++;
        if (j == 3) {
            j = 0;
        }
    }
    return password.toString();
}

private static String getRandomPasswordCharacters(int pos) {
    Random randomNum = new Random();
    StringBuilder randomChar = new StringBuilder();
    switch (pos) {
        case 0:
            randomChar.append(NUMBERS.charAt(randomNum.nextInt(NUMBERS.length() - 1)));
            break;
        case 1:
            randomChar.append(UPPER_ALPHABETS.charAt(randomNum.nextInt(UPPER_ALPHABETS.length() - 1)));
            break;
        case 2:
            randomChar.append(SPECIALCHARACTERS.charAt(randomNum.nextInt(SPECIALCHARACTERS.length() - 1)));
            break;
        case 3:
            randomChar.append(LOWER_ALPHABETS.charAt(randomNum.nextInt(LOWER_ALPHABETS.length() - 1)));
            break;
    }
    return randomChar.toString();

}
 3
Author: Prasobh.K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 06:52:26

Aquí está el código de una línea por AbacusUtil

String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())

Aleatorio no significa que deba ser único. para obtener cadenas únicas, usando:

N.uuid() // e.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
N.guid() // e.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'
 3
Author: Developer of AbacusUtil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-20 21:45:59

Mencionas "simple", pero en caso de que alguien más esté buscando algo que cumpla con los requisitos de seguridad más estrictos, es posible que quieras echar un vistazo a jpwgen. jpwgen se basa en pwgen en Unix, y es muy configurable.

 3
Author: michaelok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-26 22:47:13
public static String randomSeriesForThreeCharacter() {
    Random r = new Random();
    String value="";
    char random_Char ;
    for(int i=0; i<10;i++)
    { 
        random_Char = (char) (48 + r.nextInt(74));
        value=value+random_char;
    }
    return value;
}
 3
Author: duggu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 23:30:48

Usando la biblioteca apache se puede hacer en una línea

import org.apache.commons.lang.RandomStringUtils;
RandomStringUtils.randomAlphanumeric(64);

Aquí está doc http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/RandomStringUtils.html

 2
Author: hridayesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-15 07:52:12

Tal vez esto sea útil

package password.generater;

import java.util.Random;

/**
 *
 * @author dell
 */
public class PasswordGenerater {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int length= 11;
        System.out.println(generatePswd(length));

        // TODO code application logic here
    }
    static char[] generatePswd(int len){
        System.out.println("Your Password ");
        String charsCaps="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
        String Chars="abcdefghijklmnopqrstuvwxyz";
        String nums="0123456789";
        String symbols="!@#$%^&*()_+-=.,/';:?><~*/-+";
        String passSymbols=charsCaps + Chars + nums +symbols;
        Random rnd=new Random();
        char[] password=new char[len];

        for(int i=0; i<len;i++){
            password[i]=passSymbols.charAt(rnd.nextInt(passSymbols.length()));
        }
      return password;

    }
}
 2
Author: 2 revs, 2 users 97%user5138430,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-28 09:49:48

El Mejor Método de Generador de Cadenas Aleatorias

public class RandomStringGenerator{

    private static int randomStringLength = 25 ;
    private static boolean allowSpecialCharacters = true ;
    private static String specialCharacters = "!@$%*-_+:";
    private static boolean allowDuplicates = false ;

    private static boolean isAlphanum = false;
    private static boolean isNumeric = false;
    private static boolean isAlpha = false;
    private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
    private static boolean mixCase = false;
    private static final String capAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String num = "0123456789";

    public static String getRandomString() {
        String returnVal = "";
        int specialCharactersCount = 0;
        int maxspecialCharacters = randomStringLength/4;

        try {
            StringBuffer values = buildList();
            for (int inx = 0; inx < randomStringLength; inx++) {
                int selChar = (int) (Math.random() * (values.length() - 1));
                if (allowSpecialCharacters)
                {
                    if (specialCharacters.indexOf("" + values.charAt(selChar)) > -1)
                    {
                        specialCharactersCount ++;
                        if (specialCharactersCount > maxspecialCharacters)
                        {
                            while (specialCharacters.indexOf("" + values.charAt(selChar)) != -1)
                            {
                                selChar = (int) (Math.random() * (values.length() - 1));
                            }
                        }
                    }
                }
                returnVal += values.charAt(selChar);
                if (!allowDuplicates) {
                    values.deleteCharAt(selChar);
                }
            }
        } catch (Exception e) {
            returnVal = "Error While Processing Values";
        }
        return returnVal;
    }

    private static StringBuffer buildList() {
        StringBuffer list = new StringBuffer(0);
        if (isNumeric || isAlphanum) {
            list.append(num);
        }
        if (isAlpha || isAlphanum) {
            list.append(alphabet);
            if (mixCase) {
                list.append(capAlpha);
            }
        }
        if (allowSpecialCharacters)
        {
            list.append(specialCharacters);
        }
        int currLen = list.length();
        String returnVal = "";
        for (int inx = 0; inx < currLen; inx++) {
            int selChar = (int) (Math.random() * (list.length() - 1));
            returnVal += list.charAt(selChar);
            list.deleteCharAt(selChar);
        }
        list = new StringBuffer(returnVal);
        return list;
    }   

}
 1
Author: Bhavik Ambani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-28 07:33:52
public static String getRandomString(int length) 
{
   String randomStr = UUID.randomUUID().toString();
   while(randomStr.length() < length) {
       randomStr += UUID.randomUUID().toString();
   }
   return randomStr.substring(0, length);
}
 1
Author: Vin Ferothas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-03 06:59:05