I want to create a function to encrypt a string which will shorten the string into alphanumeric character and also create a function decrypt which will get back the encrypted string.
Here is what I coded by taking reference online.
function compress(string) {
string = unescape(encodeURIComponent(string));
var newString = '',
char, nextChar, combinedCharCode;
for (var i = 0; i < string.length; i += 2) {
char = string.charCodeAt(i);
if ((i + 1) < string.length) {
nextChar = string.charCodeAt(i + 1) - 31;
combinedCharCode = char + "" + nextChar.toLocaleString('en', {
minimumIntegerDigits: 2
});
newString += String.fromCharCode(parseInt(combinedCharCode, 10));
} else {
newString += string.charAt(i);
}
}
return newString;
}
function decompress(string) {
var newString = '',
char, codeStr, firstCharCode, lastCharCode;
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char > 132) {
codeStr = char.toString(10);
firstCharCode = parseInt(codeStr.substring(0, codeStr.length - 2), 10);
lastCharCode = parseInt(codeStr.substring(codeStr.length - 2, codeStr.length), 10) + 31;
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
} else {
newString += string.charAt(i);
}
}
return newString;
}
var stringToCompress = 'awesome';
var compressedString = compress(stringToCompress);
var decompressedString = decompress(compressedString);
console.log("encrypted :",compressedString);
console.log("decrypted :",decompressedString);
Currently the output from the sting="awesome" is
encrypted: ☼⟈⮪e
decrypted: awesome
I want similar encryption but must be only in alphanumeric values and not symbols.