Skip to content

Instantly share code, notes, and snippets.

@Gabryxx7
Last active August 18, 2021 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gabryxx7/521ead380ca3058998e96baa9a170228 to your computer and use it in GitHub Desktop.
Save Gabryxx7/521ead380ca3058998e96baa9a170228 to your computer and use it in GitHub Desktop.
Javascript token generation
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function encrypt(plaintext, key) {
let cyphertext = [];
// Convert to hex to properly handle UTF8
plaintext = Array.from(plaintext).map(function (c) {
if (c.charCodeAt(0) < 128) return c.charCodeAt(0).toString(16).padStart(2, '0');
else return encodeURIComponent(c).replace(/\%/g, '').toLowerCase();
}).join('');
// Convert each hex to decimal
plaintext = plaintext.match(/.{1,2}/g).map(x => parseInt(x, 16));
// Perform xor operation
for (let i = 0; i < plaintext.length; i++) {
cyphertext.push(plaintext[i] ^ key.charCodeAt(Math.floor(i % key.length)));
}
// Convert to hex
cyphertext = cyphertext.map(function (x) {
return x.toString(16).padStart(2, '0');
});
return cyphertext.join('');
}
// Super simple XOR decrypt function
function decrypt(cyphertext, key) {
try {
cyphertext = cyphertext.match(/.{1,2}/g).map(x => parseInt(x, 16));
let plaintext = [];
for (let i = 0; i < cyphertext.length; i++) {
plaintext.push((cyphertext[i] ^ key.charCodeAt(Math.floor(i % key.length))).toString(16).padStart(2, '0'));
}
return decodeURIComponent('%' + plaintext.join('').match(/.{1,2}/g).join('%'));
} catch (e) {
return false;
}
}
function generateRandomToken(passphrase, min, max, debug){
var randomVal = ''+getRandomInt(min, max);
var token = encrypt(passphrase.toUpperCase(), ('' + getRandomInt(min, max)).toUpperCase());
if(debug)
console.log("Token generated: " + token.toUpperCase() + "\nPassphrase: " + passphrase.toUpperCase() + "\nKey: " + randomVal);
return token;
}
function findKey(token, passphrase, min, max, debug) {
var key = -1;
for (i = min; i <= max; i++) {
var test = decrypt(token, '' + i);
if(debug)
console.log("Token: " + token.toUpperCase() + "\tKey: " + i + "\tDecrypted: " + test.toUpperCase());
if (test.toUpperCase() === passphrase.toUpperCase()) {
key = i;
}
}
if (key >= 0) {
console.log("FOUND!\nToken: " + token.toUpperCase() + "\nPassphrase: " + passphrase.toUpperCase() + "\nKey: " + key);
}
return key;
}
var min = 1;
var max = 200;
var passphrase = "sl_code!9"
var passkey = generateRandomToken(passphrase, min, max, false)
var found_key = findKey(passkey, passphrase, min, max, false)
jQuery("#random_token_voucher").text(('' + passkey).toUpperCase())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment