Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random looking code from consecutive integers [closed]

I would like to generate a 6-character alphanumeric code (eg. A3SJ8D) from a 32-bit positive integer where each code in the sequence does not appear similar to the previous.

  1. A3SJ8D
  2. G54FGS
  3. ...

This code must be reversible so that G54FGS could be translated back to 2, for example (1:1 mapping).

This "randomness" is not for security purposes but for very simple obfuscation. In other words, the method need not be "secure".

Edit

To clarify, I understand that the max possible value for an unsigned 32-bit integer, (2^32)-1, exceeds the max possible value of a 6-character alpha-numeric code using 10 digits and 26 letters, (36^6)-1. So, the positive integer to be encoded must not overflow the bounds established by the number of characters available to the code set.

Answered!

Example

Here is a simple code example in Javascript based on @nwellnhof's accepted answer below.


var Skip32 = require('skip32').Skip32,
    key = "0123456789".split("").map(function(c) { return c.charCodeAt(0) }),
    cipher = new Skip32(key),
    codelen = 6,
    radix = 36,
    max = Math.pow(radix,codelen);

function numToCode(num) {
    while ((num = cipher.encrypt(num)) >= max) {}
    return num.toString(radix).toUpperCase();
}

function codeToNum(code) {
    var num = parseInt(code,radix);
    while ((num = cipher.decrypt(num)) >= max) {}
    return num;
}
like image 642
Jonathan Hawkes Avatar asked Oct 21 '22 16:10

Jonathan Hawkes


2 Answers

I'd go with the SKIP32 cipher which is a 32-bit block cipher based on Skipjack. Simply choose a random key, encrypt the integer, and output the result in base 36. You can find a implementation in C here.

like image 139
nwellnhof Avatar answered Oct 31 '22 12:10

nwellnhof


You'll get a sequence of fairly random looking codes if you multiply 1,2,3,... by a fairly large odd integer and use base 36 to convert to string.

For example, if you multiply by 123456789 you get the following sequence for 1, 2, 3, 4:

1: 21i3v9
2: 4307qi
3: 64iblr
4: 860fh0

To reverse the operation multiply by the multiplicative inverse, for example 102505021 in the case of 123456789.

To make the sequence look a bit more "random" you can further scramble the numbers with an xor or addition.

In fact, this is how the linear congruential generator of pseudorandom numbers works.

like image 33
Joni Avatar answered Oct 31 '22 12:10

Joni