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
Written by David Long
Related protips
3 Responses
jsfuck.com
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.
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;
}
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside