Last active
July 22, 2020 20:30
-
-
Save DiegoQueiroz/dd2f72144b7e5194f85952bad45bb6fe to your computer and use it in GitHub Desktop.
Sequência de dígitos aleatórios em Java, utilizando SecureRandom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.SecureRandom; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
System.out.println(GeraDigitosAleatorios(8)); | |
} | |
public static String GeraDigitosAleatorios(int tamanho){ | |
SecureRandom random = new SecureRandom(); | |
byte bytes[] = new byte[tamanho]; | |
random.nextBytes(bytes); | |
StringBuilder sequencia = new StringBuilder(); | |
for (int i = 0; i < tamanho; i++){ | |
sequencia.append((bytes[i] - Byte.MIN_VALUE) % 100); // evita negativo | |
if (sequencia.length() >= tamanho) break; | |
} | |
return sequencia.substring(0, tamanho); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Essas funções geram sequências de DÍGITOS (números apenas) e devem ser utilizadas apenas quando essa limitação existir. Se a combinação de letras, números ou até símbolos puder ser considerada, esses métodos NÃO devem ser utilizados, pois são significativamente menos seguros.