New to Nutbox?

Affine

0 comments

drago18121996
68
6 days agoSteemit2 min read

<export const encode = (phrase, key) => {
let lower = phrase.toLowerCase().replaceAll(' ', '');
let alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'];
let m = 26;
let res = "";
let w = 0;
if(!gdc(key['a'],m)) throw new Error("a and m must be coprime.");
lower.split('').forEach((elm) =>{
if(/^[a-zA-Z]$/.test(elm)){
const index = alphabet.indexOf(elm);
const num1 = key['a'];
const num2 = key['b'];
let ex = (num1*index + num2) % m;
ex = (ex +m) % m;
res += alphabet[ex];
}
else if(!isNaN(Number(elm))){
res += elm;
}
else{return;}

w++;
if(w==5){
  res += " ";
  w = 0;
}

});
return res.trim();
};

function gdc(a,b){
while(b!=0){
let temp = b;
b = a % b;
a = temp;
}
return a === 1;
}

function mmi(a) {
let m=26;
let res = 0;
for(let i=0; i<m; i++){
if((a * i) % m === 1){
res = i;
}
}
return res;
}

export const decode = (phrase, key) => {
let m = 26;
let alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'];
let res = phrase.replaceAll(' ', '');
let resTot = "";
if(!gdc(key['a'],m)) throw new Error("a and m must be coprime.");
res.split('').forEach((elm) =>{
if(/^[a-zA-Z]$/.test(elm)){
const index = alphabet.indexOf(elm);
const num1 = key['a'];
const num2 = key['b'];
let mmiV = mmi(num1);
let dx = (mmiV * (index - num2)) % m;
dx = (dx +m) % m;
resTot += alphabet[dx];
}
else if(!isNaN(Number(elm))){
resTot += elm;
}
});
return resTot;
}

Comments

Sort byBest