Last active
June 3, 2019 18:08
-
-
Save NiuWeb/d9dd13de3518b287e537d4c6b320c607 to your computer and use it in GitHub Desktop.
Text Encoder Algorithm (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///CIFRADO | |
function Encoder() { | |
var seed = 'hEloWOrd'; //Caracteres que contienen información | |
var noseed = 'Guelcumtyjeg'; //Caracteres de relleno | |
//Número aleatorio entre 0 y limit (éste último nunca se genera) | |
function irandom(limit) { | |
return Math.floor(limit * Math.random()); | |
} | |
//Valor numérico de un caracter | |
function ord(char) { | |
return char.charCodeAt(0); | |
} | |
//Cifrar un número entero | |
this.int2base = function(int) { | |
int = Math.floor(Math.abs(int)); //Positivo y entero | |
if(int == 0) | |
return seed[0]; | |
var res = ''; //Resultado | |
while(int > 0) { | |
let rem; | |
rem = int % seed.length; | |
int = Math.floor(int / seed.length); | |
res = seed[rem] + res; | |
} | |
return res; | |
} | |
//Descifrar un número entero | |
this.base2int = function(base) { | |
var int = 0; | |
for(let i = 0; i < base.length; i++) { | |
let pos = seed.indexOf(base[i]); | |
int += pos * Math.pow(seed.length, base.length - i - 1); | |
} | |
return int; | |
} | |
//Cifrar un texto | |
this.encode = function(text) { | |
var list = []; | |
var maxn = 0; | |
for(let i = 0; i < text.length; i++) { | |
let val = ord(text[i]); | |
let sec = this.int2base(val); | |
maxn = Math.max(sec.length, maxn); | |
list.push(sec); | |
} | |
var result = (maxn<10?'0':'') + maxn.toString(); | |
list.forEach(function(item) { | |
while(item.length < maxn) { | |
item = noseed[ irandom(noseed.length) ] + item; | |
} | |
result += item; | |
}); | |
return result; | |
} | |
//Descifrar un texto | |
this.decode = function(base) { | |
var length = parseInt(base.substring(0, 2)); | |
var content = base.substring(2); | |
var result = ''; | |
for(let i = 0; i < content.length; i += length) { | |
let char = content.substring(i, i + length); | |
let j = 0; | |
while(noseed.indexOf(char[j]) !== -1) { | |
j++; | |
} | |
char = char.substring(j); | |
let val = this.base2int(char); | |
result += String.fromCharCode(val); | |
} | |
return result; | |
} | |
} | |
//Prueba | |
var E = new Encoder(); | |
var coded = E.encode('Hola Mundo!'); | |
var decoded = E.decode(coded); | |
console.log(coded, ' ', decoded); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment