Login

Django Template - obfuscate a javascript string

Author:
oriadam
Posted:
February 8, 2015
Language:
Python
Version:
1.7
Tags:
obfuscation
Score:
0 (after 0 ratings)

Obfuscate javascript strings.

  • Convert
  • {{'Pita Hummus'|js_obfuscate_string}}
  • to something like
  • 'P4itzga Hnumg7mubs'.replace(/[4zgn7b]/g,'')

Making it hard to text-search for strings in your code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@register.filter
def js_obfuscate_string(text):
	CHANCE_TO_ADD=0.2
	CHANCE_TO_ADD_INCREASE_BY=0.1
	MAX_NUMBER_OF_DIFFERENT_ADDED_CHARS=5
	import string,random
	chars=string.ascii_letters+string.digits
	unused=(list(filter((lambda x: x not in text), list(chars))))
	if len(unused)<4:
		# punctuations makes the text easy to read, add them only when there's no other choice
		chars=' [email protected]!#~`;<>|' # do not add rx meaningful chars like *+?.-\/
		unused+=(list(filter((lambda x: x not in text), list(chars))))

	unused_in_use=''
	random.shuffle(unused)
	next_chance=CHANCE_TO_ADD
	if unused and len(unused):
		output="'"
		for c in list(text):
			if random.random()<next_chance:
				if len(unused_in_use) and random.random()<=((1/float(MAX_NUMBER_OF_DIFFERENT_ADDED_CHARS))*len(unused_in_use)):
					# when more than 5 chars were already 
					added_char=random.choice(unused_in_use)
				else:
					added_char=random.choice(unused)
				output+=added_char
				next_chance=CHANCE_TO_ADD # reset chance
				if added_char not in unused_in_use:
					unused_in_use+=added_char
			else:
				next_chance+=CHANCE_TO_ADD_INCREASE_BY # increase the chance to add garbage everytime garbage was not added
			output+=c
		unused_in_use=list(unused_in_use)
		random.shuffle(unused_in_use)
		unused_in_use=''.join(unused_in_use)
		output+="'.replace(/["+unused_in_use+"]/g,'')"
	if len(unused_in_use)==0:
		# nothing was actually replaced
		output="'"+text+"'"
	return mark_safe(output)

More like this

Comments

Please login first before commenting.