Skip to content

Instantly share code, notes, and snippets.

@Alexandre-cibot
Created February 19, 2021 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alexandre-cibot/46ddfb256fa3cd0742f087abdd9d3553 to your computer and use it in GitHub Desktop.
Save Alexandre-cibot/46ddfb256fa3cd0742f087abdd9d3553 to your computer and use it in GitHub Desktop.
Vigenère cipher - Clash of Code
// Vigenère cipher
// https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
// Created for a Clash Of Code
// doesnt respect case. screw it.
function encrypt(text, code) {
text = text.toLowerCase();
code = code.toLowerCase();
const alpha = [..."abcdefghijklmnopqrstuvwxyz".repeat(2)];
let output = "";
let key = code;
while (key.length < text.length) {
key += code;
}
if (key.length !== text.length) {
key = key.slice(0, text.length);
}
for (let i = 0; i < text.length; i++) {
const letter = text[i];
if (!alpha.includes(letter)) {
output += letter;
} else {
const letterAlphaIndex = alpha.indexOf(letter);
const k = key[i];
const kAlphaIndex = alpha.indexOf(k);
output += alpha[letterAlphaIndex + kAlphaIndex];
}
}
return output;
}
function decrypt(text, code) {
text = text.toLowerCase();
code = code.toLowerCase();
const alpha = [..."abcdefghijklmnopqrstuvwxyz".repeat(2)];
let output = "";
let key = code;
while (key.length < text.length) {
key += code;
}
if (key.length !== text.length) {
key = key.slice(0, text.length);
}
for (let i = 0; i < text.length; i++) {
const letter = text[i];
if (!alpha.includes(letter)) {
output += letter;
} else {
const letterAlphaIndex = alpha.indexOf(letter);
const k = key[i];
const kAlphaIndex = alpha.indexOf(k);
let indexToget = letterAlphaIndex - kAlphaIndex;
if (indexToget < 0) {
output += alpha[26 - Math.abs(indexToget)];
} else {
output += alpha[indexToget];
}
}
}
return output;
}
const encryptedMessage = encrypt("Je suis un message secret.", "lecode");
console.log(encryptedMessage);
console.log(decrypt(encryptedMessage, "lecode"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment