The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution. ... In a Caesar cipher, each letter of the alphabet is shifted along some number of places; for example, in a Caesar cipher of shift 3, A would become D, B would become E, Y would become B and so on. The Vigenère cipher consists of several Caesar ciphers in sequence with different shift values.
"my secret code i want to secure" // message
"passwordpasswordpasswordpasswor" // key
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var key = 'password';
// creates a cipher helper with each letter substituted
// by the corresponding character in the key
var c = new VigenèreCipher(key, alphabet);
c.encode('codewars'); // returns 'rovwsoiv'
c.decode('laxxhsj'); // returns 'waffles'
c.encode('CODEWARS'); // returns 'CODEWARS'
function VigenèreCipher(key,abc){
this.encode = function(str){
//对str进行分割,确认是否在字母表中,然后按照
return str.split('').map((item,i)=>{
//按照key和abc中的位置,进行移动找到当前所在的位置
return abc.indexOf(item) > -1 ?
abc[(abc.indexOf(item) + abc.indexOf(key[i % key.length])) % abc.length]
: item;
}).join('');
}
this.decode = function(str){
//与encode相反,获得坐标在移动回来
return str.split('').map((item,i)=>{
//按照key和abc中的位置,进行移动找到当前所在的位置
return abc.indexOf(item) > -1 ?
abc[( abc.length + abc.indexOf(item) - abc.indexOf(key[i % key.length]) ) % abc.length]
: item;
}).join('');
}
}
Question From : https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3/train/javascript
转载请注明出处: https://chrunlee.cn/article/code-war-cipher-helper.html