1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
package cle;
import java.util.Random;
public class KeyGen {
private static String CARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static int TAILLE_CLE = 16;
private static int MODULO = 997;
private static int VOULU = 500;
public static void main(String[] args) {
new KeyGen().gen(1000);
}
private void gen(int i) {
// Clé de départ
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < TAILLE_CLE; j++) {
sb.append(CARS.charAt(random.nextInt(TAILLE_CLE)));
}
// boucle de recherche
do {
int hash = hash(sb.toString());
System.out.println(sb + " :" + hash);
if(hash == VOULU) {
break;
}
sb.setCharAt(random.nextInt(TAILLE_CLE), CARS.charAt(random.nextInt(CARS.length())));
} while(true);
}
/**
* Calcule le hash de la clé, avec modulo
* @param key
* @return
*/
private int hash(String key) {
if(key == null || key.length() != TAILLE_CLE) {
throw new IllegalArgumentException("Clé invalide: " + key);
}
key = key.toUpperCase();
int n = 0;
for (int i = 0; i < key.length(); i++) {
char car = key.charAt(i);
int index = CARS.indexOf(car);
if(index == -1) {
throw new IllegalArgumentException("Caractère de la clé invalide: " + car);
}
n += (i + 1) * index;
}
return n % MODULO;
}
} |
Partager