ROT13 Implementation in Javascript and Ruby

1 minute read

While rot13 cannot be used for encrypting important information, it can be used in places where security is not that much of a concern. One typical ues case: Suppose we are building an amazon product review site. All of our affiliate links in the site are to be used carefully. If Amazon detects abuse (multiple illegal clicks), then they’ll cancel the affiliation and we won’t be earning any commission off the clicks.

One main concern is our links can be abused by internet bots. They’ll be crawled and accessed without our permission. This would lead Amazon to suspect us and might lead to account cancellation. In that case, we can rot13 the affiliate links in the server (using say ruby), and when the page loads in the browser, javascript can be used to decrypt it back to the actual links using rot13 (rot13 is its own reverse).

So here’s rot13 in ruby:

def rot13(str)"A-Ma-mN-Zn-z","N-Zn-zA-Ma-m")

And here’s rot13 in javascript:

function rot13(str) {
  var func = function(c) {
    return String.fromCharCode(
      (c <= "Z" ? 90 : 122)
      (c = c.charCodeAt(0) + 13)
        c - 26
  return str.replace(/[a-zA-Z]/g, func)

Documentation on the methods used: