2009-11-16 28 views
11

me quieren dar quizá una contraseña millones a algunos usuarios que deben ser como:¿Cómo puedo crear una contraseña?

  1. Se debe tener al menos 6 caracteres
  2. Se debe tener dígitos y también cartas

¿Debo usar Random aquí? ¿Cómo?

+1

vi un interesante haciendo lución del problema "aleatorio" cuando me inscribí en mis códigos de firma de RIM. Te hacen mover el mouse una tonelada completa para generar datos verdaderamente aleatorios, en lugar de tener hardware dedicado para hacer lo mismo. –

+0

¿Es un requisito aleatorio? Si no, simplemente itere sobre 000000 a 999999 y AA-ZZ. –

Respuesta

34

RandomStringUtils de Apache Commons Lang proporcionan algunos métodos para generar un estudio aleatorizado Cadena, que puede usarse como contraseña.


Estos son algunos ejemplos de 8 caracteres de las contraseñas de la creación:

// Passwords with only alphabetic characters. 
for (int i = 0; i < 8; i++) { 
    System.out.println(RandomStringUtils.randomAlphabetic(8)); 
} 
System.out.println("--------"); 
// Passwords with alphabetic and numeric characters. 
for (int i = 0; i < 8; i++) { 
    System.out.println(RandomStringUtils.randomAlphanumeric(8)); 
} 

que crea el siguiente resultado:

zXHzaLdG 
oDtlFDdf 
bqPbXVfq 
tzQUWuxU 
qBHBRKQP 
uBLwSvnt 
gzBcTnIm 
yTUgXlCc 
-------- 
khDzEFD2 
cHz1p6yJ 
3loXcBau 
F6NJAQr7 
PyfN079I 
8tJye7bu 
phfwpY6y 
62q27YRt 

Por supuesto, también hay métodos que pueden restringir el conjunto de caracteres permitidos para la generación de contraseñas:

for (int i = 0; i < 8; i++) { 
    System.out.println(RandomStringUtils.random(8, "abcDEF123")); 
} 

creará sólo contraseñas con los caracteres a, b, c, D, E, F, 1, 2 o 3:

D13DD1Eb 
cac1Dac2 
FE1bD2DE 
2ab3Fb3D 
213cFEFD 
3c2FEDDF 
FDbFcc1E 
b2cD1c11 
+0

+1 el 'randomAlphabetic' y' randomAlphaNumeric' son buenos para esto, a menos que quieras contraseñas criptográficamente aleatorias. – skaffman

+2

El enlace está roto –

+0

Enlace corregido ... – romaintaz

10

Use SecureRandom, proporciona contraseñas más aleatorias.

Puede crear una sola contraseña usando algo como esto (nota: código no probado).

// put here all characters that are allowed in password 
char[] allowedCharacters = {'a','b','c','1','2','3','4'}; 

SecureRandom random = new SecureRandom(); 
StringBuffer password = new StringBuffer(); 

for(int i = 0; i < PASSWORD_LENGTH; i++) { 
    password.append(allowedCharacters[ random.nextInt(allowedCharacters.length) ]); 
} 

Tenga en cuenta que este no garantiza que el cada contraseña tendrá dos dígitos y caracteres.

+0

SecureRandom devuelve números, pero ella pidió números y letras. – Sylar

+0

Este código hace referencia a una matriz de caracteres por el valor entero devuelto, por lo que sí devuelve caracteres y números. – badbod99

+0

Sí, ahora, pero antes de la edición no fue así. – Sylar

1

Lo que me gustaría hacer es algo como esto:

  1. crear dos tablas, una con las letras necesarias y otra con los dígitos permitidos.
  2. Use Aleatorio para decidir la longitud de la contraseña.
  3. Use Aleatorio para decidir si el siguiente carácter es una letra o un dígito.
  4. Use Random una vez más para generar un índice para la matriz de letras o dígitos (según lo que haya obtenido en el paso 3). Añade el carácter obtenido a la contraseña.
  5. Repetir desde 3 hasta que tenga la cantidad de caracteres obtenido en 2.
+0

esto no garantiza los dígitos y letras en la contraseña –

+0

@jk: Tiene razón. Luego, la contraseña debe verificarse al final del proceso, y si contiene solo letras o solo dígitos, puede descartarse y reiniciarse el proceso o pueden agregarse algunos caracteres del grupo faltante manualmente. De todos modos esto debería suceder rara vez. – Konamiman

0

Ésta será la más fácil :)

String char_group = "abcdefghijklmnopqrstuvwxyz"; 
String digit_group = "123456789"; 

// first choose a len of pwd 
Random ran = new Random(); 
int pwd_len = ran.nextInt(50); //50 is the max length of password,say 
// check that pwd_len is not less than 6 
// do the check here 

// finally create the password.. 
StringBuffer pwd = new StringBuffer(); 
Random RNG = new Random(); 
for (int i = 0; i < pwd_len ; i++) { 
    int randomNum = RNG.nextInt(100); 
    char c = ''; 
    // Here 25% is the ratio of mixing digits 
    // in the password, you can change 4 to any 
    // other value to change the depth of mix 
    // or you can even make it random. 
    if (randomNum % 4 == 0) { 
     c = digit_group[randomNum % digit_group.length]; 
    } else { 
     c = char_group[randomNum % char_group.length]; 
    } 
    pwd.append(c); 
} 
return pwd.toString(); 
+4

Esto inicializa el generador de números aleatorios dentro del ciclo, usando la hora actual. La contraseña no será muy aleatoria. La contraseña también generada puede contener caracteres no imprimibles. –

+0

@juha ... eso definitivamente es correcto, tal vez estaba medio dormido mientras respondía esto ... actualizaré la respuesta :) –

+0

HEY GUYS .... HE ACTUALIZADO MI RESPUESTA ... POR FAVOR RETIREN SUS VOTOS ABAJO:) –

3

Esta es también una agradable:

String password = Integer.toString((int) (Math.random() * Integer.MAX_VALUE), 36); 

Se sin embargo, no garantiza que la contraseña siempre contenga ambos dígitos y letras, pero la mayoría de las sugerencias anteriores tampoco lo hacen.

4

Aquí hay una que escribí hace un tiempo:

package com.stackoverflow.does.my.code.for.me; 

import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.util.ArrayList; 
import java.util.List; 

public class PasswordUtil { 

    /** Minimum password length = 6 */ 
    public static final int MIN_PASSWORD_LENGTH = 6; 
    /** Maximum password length = 8 */ 
    public static final int MAX_PASSWORD_LENGTH = 8; 

    /** Uppercase characters A-Z */ 
    public static final char[] UPPERS = new char[26]; 
    /** Lowercase characters a-z */ 
    public static final char[] LOWERS = new char[26]; 
    /** 
    * Printable non-alphanumeric characters, excluding space. 
    */ 
    public static final char[] SPECIALS = new char[32]; 
    public static final char[] DIGITS = new char[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 

    static { 
     // Static initializer block for populating arrays 
     int U = 'A'; 
     int l = 'a'; 
     int d = '0'; 
     for (int i = 0; i < 26; i++) { 
      UPPERS[i] = (char) (U + i); 
      LOWERS[i] = (char) (l + i); 
      if (i < 10) { 
       DIGITS[i] = (char) (d + i); 
      } 
     } 
     int p = 0; 
     for (int s = 33; s < 127; s++) { 
      char specialChar = (char) 32; 

      if (s >= 'a' && s <= 'z') 
       s = 'z' + 1; // jump over 'a' to 'z' 
      else if (s >= 'A' && s <= 'Z') 
       s = 'Z' + 1; // jump over 'A' to 'Z' 
      else if (s >= '0' && s <= '9') 
       s = '9' + 1; // jump over '0' to '9' 

      specialChar = (char) s; 
      SPECIALS[p] = specialChar; 
      p++; 
     } 
    } 

    public String generatePassword() { 
     List<char[]> activeSets = new ArrayList<char[]>(4); 
     List<char[]> inactiveSets = new ArrayList<char[]>(4); 

     activeSets.add(UPPERS); 
     activeSets.add(LOWERS); 
     activeSets.add(SPECIALS); 
     activeSets.add(DIGITS); 

     SecureRandom random = new SecureRandom(); 

     int passwordLength = 5 + random.nextInt(3); 
     StringBuffer password = new StringBuffer(passwordLength + 1); 

     for (int p = 0; p <= passwordLength; p++) { 
      char[] randomSet = null; 
      if (activeSets.size() > 1) { 
       int rSet = random.nextInt(activeSets.size()); 
       randomSet = activeSets.get(rSet); 
       inactiveSets.add(randomSet); 
       activeSets.remove(rSet); 
      } else { 
       randomSet = activeSets.get(0); 
       inactiveSets.add(randomSet); 
       activeSets.clear(); 
       activeSets.addAll(inactiveSets); 
       inactiveSets.clear(); 
      } 
      int rChar = random.nextInt(randomSet.length); 
      char randomChar = randomSet[rChar]; 
      password.append(randomChar); 
     } 

     return password.toString(); 
    } 
} 
24

Cuando se utiliza de RandomStringUtils por razones de seguridad Apache (es decir contraseñas), es muy importante combinar el uso de una fuente SecureRandom:

RandomStringUtils.random(6, 0, 0, true, true, null, new SecureRandom()); 
0

Un poco tarde, pero suelo usar el siguiente código:

private static final int PASSWORD_SIZE = 16; 
private static final String VALID_SPECIAL_CHARACTERS = "[email protected]#$%&*()_-+=[]{}\\|:/?.,><"; // Note the double \ as escape 

private static String createPassword() { 
    SecureRandom random = new SecureRandom(); 
    StringBuilder password = new StringBuilder(); 
    while (password.length() < PASSWORD_SIZE) { 
     char character = (char) random.nextInt(Character.MAX_VALUE); 
     if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || VALID_SPECIAL_CHARACTERS.contains(String.valueOf(character))) { 
      password.append(character); 
     } 
    } 
    return password.toString(); 
} 

No hay garantía de que siempre haya un número, carácter especial, minúsculas y mayúsculas en la contraseña. Esto podría hacerse cumplir añadiendo primero un carácter y un dígito, sin embargo, esto crearía contraseñas que son un poco más predecibles.

0

Aquí es cómo puede asegurarse de que su contraseña generada cumple sus criterios de contraseña, por ejemplo: en su caso, me gustaría utilizar esta expresión regular:

<code>String regex = "^(?=[a-zA-Z0-9ñÑ]*\d)(?=[a-zA-Z0-9ñÑ]*[a-z])(?=[a-zA-Z0-9ñÑ]*[A-Z])[a-zA-Z0-9ñÑ]{6,}$"</code> 

Esta expresión regular cumpla con los siguientes criterios:

1 .- por lo menos 1 letra minúscula

2.- al menos 1 letra mayúscula

3.- al menos 1 dígitos (número)

4.- al menos 6 caracteres (tenga en cuenta que agregar un número mayor que 6 después de la coma al final de la expresión regular, ahora cumplirá un criterio de al menos 6 caracteres y un máximo de lo que ponga ahí)

<code>char[] char = {'a','b','c','d','e','f','g','h',...}; 

SecureRandom random = new SecureRandom(); 
StringBuffer password = new StringBuffer();</code> 

while(!password.toString().matches("your regex")){ 
    for(int i = 0; i < 8; i++) { 
    password.append(char [ random.nextInt(char .length) ]); 
    } 
} 
System.out.println(password.toString()); 

lo que hace este código es que while su contraseña generada no cumple con sus criterios, que se repetirá el bucle for una y otra vez.

0

Implementado un PasswordBuilder. Admite límite de passwrod, debe tener caracteres y cuánto de ellos, rangos de caracteres y una lista de ellos.

uso Ejemplo: resultado

System.out.println(new PasswordBuilder().addCharsOption("[email protected]#$%&*()_-+=[]{}\\|:/?.,><", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).build()); 

Ejemplo: QU1GY7p+j+-PUW+_

System.out.println(new PasswordBuilder().addCharsOption("[email protected]#$%&*()_-+=[]{}\\|:/?.,><", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).setSize(5).build()); 

Ejemplo resultado: %,4NX

Implementación:

//Version=1.0 
//Source=https://www.dropbox.com/s/3a4uyrd2kcqdo28/PasswordBuilder.java?dl=0 
//Dependencies=java:7 com.google.guava:guava:18.0 commons-lang:commons-lang:2.6 

import com.google.common.primitives.Chars; 
import org.apache.commons.lang.ArrayUtils; 

import java.security.SecureRandom; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 

/** 
* Created by alik on 5/26/16. 
*/ 
public class PasswordBuilder { 
    private int size = 16; 
    private List<Character> options = new ArrayList<>(); 
    private Map<List<Character>, Integer> musts = new java.util.LinkedHashMap<>(); 
    private SecureRandom secureRandom = new SecureRandom(); 

    public PasswordBuilder() { 
    } 

    public PasswordBuilder setSize(int size) { 
     this.size = size; 
     return this; 
    } 

    public PasswordBuilder addRangeOption(char from, char to, int mustCount) { 
     List<Character> option = new ArrayList<>(to - from + 1); 
     for (char i = from; i < to; ++i) { 
      option.add(i); 
     } 
     return addOption(option, mustCount); 
    } 

    public PasswordBuilder addCharsOption(String chars, int mustCount) { 
      return addOption(Chars.asList(chars.toCharArray()), mustCount); 
    } 

    public PasswordBuilder addOption(List<Character> option, int mustCount) { 
     this.options.addAll(option); 
     musts.put(option, mustCount); 
     return this; 

    } 

    public String build() { 
     validateMustsNotOverflowsSize(); 
     Character[] password = new Character[size]; 

     // Generate random from musts 
     for (Map.Entry<List<Character>, Integer> entry : musts.entrySet()) { 
      for (int i = 0; i < entry.getValue(); i++) { 
       int charIndex = secureRandom.nextInt(entry.getKey().size()); 
       char c = entry.getKey().get(charIndex); 
       addChar(password, c); 
      } 
     } 

     // Generate from overall 
     for (int i = 0; i < password.length; i++) { 
      if (password[i] != null) continue; 
      password[i] = options.get(secureRandom.nextInt(options.size())); 
     } 
     return new String(ArrayUtils.toPrimitive(password)); 
    } 

    private void addChar(Character[] password, char c) { 
     int i; 
     for (i = secureRandom.nextInt(password.length); password[i] != null; i = secureRandom.nextInt(password.length)) { 
     } 
     password[i] = c; 
    } 

    private void validateMustsNotOverflowsSize() { 
     int overallMusts = 0; 
     for (Integer mustCount : musts.values()) { 
      overallMusts += mustCount; 
     } 
     if (overallMusts > size) { 
      throw new RuntimeException("Overall musts exceeds the requested size of the password."); 
     } 
    } 

    public static void main(String[] args) { 
     System.out.println(new PasswordBuilder().addCharsOption("[email protected]#$%&*()_-+=[]{}\\|:/?.,><", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).build()); 
     System.out.println(new PasswordBuilder().addCharsOption("[email protected]#$%&*()_-+=[]{}\\|:/?.,><", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).setSize(5).build()); 
    } 
} 
Cuestiones relacionadas