Skip to content

Instantly share code, notes, and snippets.

@fish2000
Last active April 24, 2019 21:02
Show Gist options
  • Save fish2000/bde99ecde5847cbf1427977c836d18db to your computer and use it in GitHub Desktop.
Save fish2000/bde99ecde5847cbf1427977c836d18db to your computer and use it in GitHub Desktop.
Django string signing in JavaScript (using String object prototypes)
/// Makes use of “hashes.js” -- q.v. https://git.io/fjsmQ
(function (hashes, undefined) {
var SIGNATURE_LENGTH = 27,
SIGNATURE_SALT = 'django.core.signing.Signer',
SIGNATURE_SECRET = 'YO DOGG',
SIGNATURE_SEPARATOR = ':',
SIGNATURE_DJANGO_SALT = 'signer';
String.prototype.chomp = (function (regex, undefined) {
return function () {
var arg = arguments[0] || undefined,
chomper = (arg === undefined)
? regex
: new RegExp("(" + arg + ")+$");
return this.replace(chomper, '');
};
})(/(\s|\n|\r)+$/);
if (hashes !== undefined) {
/// Django-compatible string signatures
String.prototype.signature = (function (SHA1, padding) {
return function (key_secret, salt) {
var sha1 = new SHA1({ utf8: false, b64pad: padding }),
key = sha1.raw(salt + key_secret),
hmac64 = sha1.setPad(padding).b64_hmac(key, this).chomp();
return hmac64.replace(/\//g, '_').replace(/\+/g, '-'); /// Replacements are a Django thing
};
})(hashes.SHA1, ' ');
String.prototype.sign = function () {
var key_secret = arguments[0] || SIGNATURE_SECRET,
key_salt = arguments[1] || SIGNATURE_SALT,
sep = arguments[2] || SIGNATURE_SEPARATOR,
salt = key_salt + SIGNATURE_DJANGO_SALT,
signature = this.signature(key_secret, salt);
return (this + sep + signature);
};
String.prototype.unsign = function () {
var key_secret = arguments[0] || SIGNATURE_SECRET,
key_salt = arguments[1] || SIGNATURE_SALT,
sep = arguments[2] || SIGNATURE_SEPARATOR,
salt = key_salt + SIGNATURE_DJANGO_SALT,
split = this.split(sep),
sig = split.pop(),
orig = split.join(sep),
signature = orig.signature(key_secret, salt);
return sig == signature ? orig : false;
};
String.prototype.voidsign = function () {
var sep = arguments[0] || SIGNATURE_SEPARATOR,
split = this.split(sep),
sig = split.pop(),
orig = split.join(sep);
return (this.indexOf(sep) !== -1 && sig.length === SIGNATURE_LENGTH) ? orig : this.toString();
};
}
})(window['Hashes']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment