Skip to content

Instantly share code, notes, and snippets.

@olastor
Last active November 4, 2024 09:57
Show Gist options
  • Save olastor/54c78a3d29c69806c57a32eff32f191a to your computer and use it in GitHub Desktop.
Save olastor/54c78a3d29c69806c57a32eff32f191a to your computer and use it in GitHub Desktop.
Simple algorithm to quickly obfuscate a string in javascript.
/**
* Obfuscate a plaintext string with a simple rotation algorithm similar to
* the rot13 cipher.
* @param {[type]} key rotation index between 0 and n
* @param {Number} n maximum char that will be affected by the algorithm
* @return {[type]} obfuscated string
*/
String.prototype.obfs = function(key, n = 126) {
// return String itself if the given parameters are invalid
if (!(typeof(key) === 'number' && key % 1 === 0)
|| !(typeof(key) === 'number' && key % 1 === 0)) {
return this.toString();
}
var chars = this.toString().split('');
for (var i = 0; i < chars.length; i++) {
var c = chars[i].charCodeAt(0);
if (c <= n) {
chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + key) % n);
}
}
return chars.join('');
};
/**
* De-obfuscate an obfuscated string with the method above.
* @param {[type]} key rotation index between 0 and n
* @param {Number} n same number that was used for obfuscation
* @return {[type]} plaintext string
*/
String.prototype.defs = function(key, n = 126) {
// return String itself if the given parameters are invalid
if (!(typeof(key) === 'number' && key % 1 === 0)
|| !(typeof(key) === 'number' && key % 1 === 0)) {
return this.toString();
}
return this.toString().obfs(n - key);
};
@marcofbb
Copy link

marcofbb commented Apr 10, 2020

Equivalent in PHP

function rotn($txt, $shift = 13, $n = 126) {
	$array_text = str_split($txt);
	foreach($array_text as $key => $value){
		if(ord($value) <= $n){
			$new_ascii = (ord($value) + $shift);
			if($new_ascii >= 0){
				$array_text[$key] = chr($new_ascii);
			} else {
				$array_text[$key] = chr($n + $new_ascii);
			}
		}
	}
    return implode('',$array_text);
}
$txt = 'Hello Word';
echo rotn($txt);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment