Files
JavaScript/Ciphers/keyFinder.js
Wan Cheuk Lun a93d5cfe67 Update keyFinder.js
1. modified the identifiers and used the suitable identifiers for the variables
2. leave the loop when a key is match and found to increase the speed of searching in this stage of development
3. return the key number if founded, return 0 if found nothing
2018-10-31 10:10:17 +08:00

27 lines
1.5 KiB
JavaScript

/******************************************************
Find and retrieve the encryption key automatically
Note: This is a draft version, please help to modify, Thanks!
******************************************************/
function keyFinder(str){ // str is used to get the input of encrypted string
const wordbank =["is","Is","am","Am","are","Are","have","Have","has","Has","may","May","be","Be"];
let key = 0; // return zero means the key can not be found
let inStr = str.toString(); //convert the input to String
let outStr = ""; // store the output value
let wordInOutStr = ""; // temporary store the word inside the outStr, it is used for comparison
for (let i=0; i<(52); i++){ //try the number of key shifted, the sum of character from a-z and A-Z is 26*2=52
outStr = caesarCipherEncodeAndDecodeEngine(inStr,i); // use the encrytpion engine to decrypt the input string, shiftNum=i
for ( let i=0; i<wordbank.length; i++){
// use a loop to find the next digit of wordbank element and compare with outStr's digit
for ( let j=0; j < wordbank[i].length; j++){
wordInOutStr += outStr[i+j];
}
// this part need to be optimize with the calculation of the number of occurance of word's probabilities
// linked list will be used in the next stage of development to calculate the number of occurace of the key
if (wordbank[i] == wordInOutStr){
return key=i; // return the key number if founded
}
}
}
return 0; // return 0 if found nothing
}