我正在尝试制作一个playfair密码方生成器。
如果你知道那是什么,那么你就知道你有一把钥匙然后进入一个正方形,其中不在键中的其余字母按字母顺序输入(也删除了J键)。 / p>
所以目前我有这个功能:
function square(usrInputKey){
var alpha = ["A","B","C","D","E","F","G","H","I","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var key = usrInputKey.toUpperCase()
keyword = key.split('')
var keysquare=keyword
count=keyword.length
for (var p=0;p<alpha.length;p++) {
//document.write(" Alpha: " + alpha[p] + "<br>")
if ( keyword[0] != alpha[p] && keyword[1] != alpha[p] && keyword[2] != alpha[p] ) {
keysquare[count]=alpha[p]
count++
}
}
return keysquare
}
该函数具有关键字的输入,该关键字是用于测试perposes的单词键。
此功能有效,输出为:K,E,Y,A,B,C,D,F,G,H,I,L,M,N,O,P,Q,R,S,T, U,V,W,X,Z
但是只有在关键字长度为3个字符时才有效。如果它使用任何数量的关键字而不是硬编码3或者具有不同可能长度的语句,我希望它。
我尝试过.every(),但是只检查一个数组字符,然后输出密钥,然后输出完整的字母,包括密钥中的字母。
任何人都可以解决这个问题吗?还是必须硬编码到某个密钥长度?
答案 0 :(得分:1)
这是一个生成所需表格的函数,以及一些茉莉花测试,只是因为:
describe('Key generator test', function () {
var wordControl = {};
var alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
beforeEach(function() {
alphabet.forEach(function(letter) {
wordControl[letter] = 0;
});
});
function square(key) {
var result = [];
key = key.toUpperCase();
key = key.replace('J', 'I');
var keyArray = key.split('');
keyArray.forEach(function(letter) {
if(wordControl[letter] == 0) {
result.push(letter);
wordControl[letter] = 1;
}
});
alphabet.forEach(function(letter) {
if(wordControl[letter] == 0) {
result.push(letter);
}
});
return result;
}
it('should generate a table starting with tke key followed by the sorted alphabet', function() {
var key = 'KAWABANGA';
var generatedTable = square(key);
expect(generatedTable.join('')).toEqual('KAWBNGCDEFHILMOPQRSTUVXYZ');
});
it('should replace J with I', function() {
var key = 'JONAS';
var generatedTable = square(key);
expect(generatedTable.join('')).toEqual('IONASBCDEFGHKLMPQRTUVWXYZ');
});
it('should not fail due to key being more than 25 characters', function() {
var key = 'QWERTYUIOPASDFGHJKLZXCVBNMMNBVCXZLKJHGFDSAPOIUYTREWQ';
var generatedTable = square(key);
expect(generatedTable.join('')).toEqual('QWERTYUIOPASDFGHKLZXCVBNM');
});
});
我猜你仍然需要在5x5矩阵中转换结果数组,以便继续使用playfair密码算法。如果你遇到麻烦,请告诉我。
答案 1 :(得分:0)
我认为这是一个有效的例子。 join和console.log是为了我的方便。
function square(usrInputKey){
var alpha = ["A","B","C","D","E","F","G","H","I","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var key = usrInputKey.toUpperCase();
keyword = key.split('');
var newAlpha = [];
for (var k = 0; k < alpha.length; k++) {
found = false;
for (var j = 0; j < key.length; j++) {
if (alpha[k].indexOf(key[j]) > -1){
found = true;
}
}
if (!found){
newAlpha.push(alpha[k]);
}
}
newArray = keyword.concat(newAlpha);
return newArray.join(',');
}
console.log(square('KEYWORD'));
另外,在适当情况下使用分号是很好的主意(行尾等)