Last Updated: June 23, 2016
·
12.24K
· davidlong03

Simple method to obfuscate strings in JavaScript

This is a super simple hashing algorithm to take a string and obfuscate it to not be human readable. The hashed string is a case sensitive hash and pretty difficult to decrypt by simple approaches.

String.prototype.obfuscate = function () {
    var bytes = [];
    for (var i = 0; i < this.length; i++) {
        bytes.push(this.charCodeAt(i));
    }
    return bytes.join('');
}

The code simply takes each character in the string, finds the character code for it, and stores it in an array. At the end of the array, we then join it with an empty string resulting in a numeric representation of the string that you can use for comparisons.

See the function in action on jsFiddle

3 Responses
Add your response

jsfuck.com

over 1 year ago ·

Hmm this is definitely useful in some cases, but I'm not sure I'd call it "obfuscate" if you can't really get the original string back.

over 1 year ago ·

Here's a reversible version:
String.prototype.obfuscate = function () { var bytes = []; for (var i = 0; i < this.length; i++) { var charCode = this.charCodeAt(i); // pad the string to 3 digits charCode = String("000" + charCode).slice(-3); bytes.push(charCode); } return bytes.join(''); } String.prototype.deobfuscate = function () { var string = ""; var chunks = this.match(/.{1,3}/g); for (var i = 0; i < chunks.length; i++) { string += String.fromCharCode(parseInt(chunks[i], 10)); } return string; }

over 1 year ago ·