Login

Email obfuscation filter using ROT13

Author:
worksology
Posted:
April 28, 2009
Language:
Python
Version:
1.2
Score:
10 (after 10 ratings)

An email address obfuscation template filter based on the ROT13 Encryption function in Textmate's HTML bundle.

The filter should be applied to a string representing an email address. You can optionally pass the filter an argument that will be used as the email link text (otherwise it will simply use the email address itself).

Example usage:

{{ email_address|obfuscate:"Contact me!" }}

or

{{ email_address|obfuscate }}

Of course, you can also use this on hardcoded email addresses, like this:

{{ "[email protected]"|obfuscate }}

 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
import re
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape
from django.template import Library

register = Library()

@register.filter()
def obfuscate(email, linktext=None, autoescape=None):
    """
    Given a string representing an email address,
	returns a mailto link with rot13 JavaScript obfuscation.
	
    Accepts an optional argument to use as the link text;
	otherwise uses the email address itself.
    """
    if autoescape:
        esc = conditional_escape
    else:
        esc = lambda x: x

    email = re.sub('@','\\\\100', re.sub('\.', '\\\\056', \
        esc(email))).encode('rot13')

    if linktext:
        linktext = esc(linktext).encode('rot13')
    else:
        linktext = email

    rotten_link = """<script type="text/javascript">document.write \
        ("<n uers=\\\"znvygb:%s\\\">%s<\\057n>".replace(/[a-zA-Z]/g, \
        function(c){return String.fromCharCode((c<="Z"?90:122)>=\
        (c=c.charCodeAt(0)+13)?c:c-26);}));</script>""" % (email, linktext)
    return mark_safe(rotten_link)
obfuscate.needs_autoescape = True

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

benjaoming (on May 26, 2009):

This is brilliant! Thank you!

#

wojas (on March 19, 2010):

Excellent, thanks!

#

googol (on February 15, 2011):

Great! How do you translate the string "Contact me!"? You can't do this:

{{ email_address|obfuscate: {% trans "Contact me!" %} }}

#

gregb (on May 17, 2011):

Just a caveat: too many document.write calls seem to wreak havoc with Firefox and Chrome, deleting the whole document rather than writing in place. (Safari was fine, no idea about IE). I had to rewrite this to write in the link tags on DOM ready.

#

Please login first before commenting.