If I have a specific key length say 4 and a given ciphertext, how do I use str.matches("^[a-zA-Z0-9\\-#\\.\\!\\;\\,\\(\\)\\/%&\\s]*$"))
to find a key in order to get the plaintext.
So far I have a class for generating strings of a fixed size:
class Get {
char[] alphabet; // stores all possible letters as a character array
int keyLength; // how long the key is
int x = 0; // internal count of the number of strings generated
int max; // maximum number of strings to be generated
/*
* keyLength: length of the key strings to be generated
*/
Guess(int keyLength) {
alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray(); // use English's
this.keyLength = keyLength; // save key length
this.max = (int) Math.pow(alphabet.length, keyLength) - 1; // maximum number of guesses
}
/*
* Generate a new string of keyLength long
* Returns null if all strings have been generated
*/
String gen() {
String ret = null;
if(x < max) {
char[] c = new char[keyLength];
int[] y = toDigits(x);
for(int i = 0; i<keyLength; i++) {
c[i] = alphabet[y[i]];
}
ret = new String(c);
x = x + 1;
}
return ret;
}
/*
* Convert a number x into digits using the size of the alphabet as base
*/
int[] toDigits(int x) {
int[] ret = new int[keyLength];
for(int i = 1; i <= keyLength; i++) {
ret[keyLength - i] = x % alphabet.length;
x = x / alphabet.length;
}
return ret;
}
I want to learn how to write a method that will go through all possible keys, trying them to see if the ciphertext is a plaintext, and if it is print the message and the key it found