Skip to content

Instantly share code, notes, and snippets.

@EnzoDiazDev
Last active August 13, 2021 21:17
Show Gist options
  • Save EnzoDiazDev/a6d9275f3eb96fc4bb4bb0049b3a41f6 to your computer and use it in GitHub Desktop.
Save EnzoDiazDev/a6d9275f3eb96fc4bb4bb0049b3a41f6 to your computer and use it in GitHub Desktop.
Cifrado de Vigenere
class VigenereCipher {
constructor(key, alphabet){
this.alphabet = alphabet;
this.key = key;
this.l = alphabet.length;
}
repeat_key(length){
let new_key = this.key;
while(new_key.length < length){
new_key = new_key.repeat(2)
}
return new_key.slice(0, length + 1);
}
encode(str) {
const key = this.repeat_key(str.length)
return str
.split("")
.map((x, i) => {
const xi = this.alphabet.indexOf(x);
const k = key[i];
const ki = this.alphabet.indexOf(k);
if(xi === -1) return x;
const ei = (xi + ki) % this.l
return this.alphabet[ei];
})
.join("");
}
decode(str) {
const key = this.repeat_key(str.length)
return str
.split("")
.map((c, i) => {
const ci = this.alphabet.indexOf(c);
const k = key[i];
const ki = this.alphabet.indexOf(k);
if(ci === -1) return c;
let di;
if((ci - ki) < 0) di = di = (ci - ki + this.l) % this.l;
else di = (ci - ki) % this.l;
return this.alphabet[di];
})
.join("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment