Reputation: 13
We have numbers from 1 to 999999 we need to encrypt with an easy algorithm. The encrypted output should be human readable characters (A-Z, 0-9) and no longer than 6 digits.
Is it possible with a simple algorith to encrypt the number 123456 to e.g. GH6ZT3 and later decrypt GH6ZT3 to 123456 ?
I only can find examples with Base32 or Base64 encryption, but encrypted output is much greater than 6 digits :-(
Upvotes: 1
Views: 2358
Reputation: 24587
If you simply want to obfuscate these numbers, then it can be done quite easily with a combination of modular arithmetic and base 36 strings.
Here are a couple of functions that will work with any number from 0 to (366 − 1):
// Convert an integer (from 0 to 2176782335) into a 6-digit string in base 36.
// The result is obfuscated by using modular arithmetic, i.e. multiply by the
// (arbitrarily selected) prime number 1708159939 modulo 36^6 (2176782336)
public static String obfuscate(Long n) {
Long x;
x = (n * 1708159939L) % 2176782336L;
return String.format("%6s",Long.toString(x, 36).toUpperCase()).replace(' ','0');
}
// Inverse of the above function. Converts a 6-character base 36 string into
// an integer value. The number 1553655019 is the modular inverse of 1708159939
// (i.e., 1708159939 * 1553655019 = 1 (mod 36^6)
public static Long deobfuscate(String s) {
return (Long.valueOf(s, 36) * 1553655019L) % 2176782336L;
}
Bear in mind, however, that the obfuscated strings will include every word of 6 letters or fewer. That includes all the four-letter words.
Upvotes: 3
Reputation: 8490
If you encrypt you want a Human non-readable way to represent the number.
To do what you want, you should change the base of the number. Something as hexadecimal (base 16) should give some good results. Try another base, as 20.
Take a look at: In Java how do you convert a decimal number to base 36?
Or, you can choose a Classical Criptography, like in Ancient Rome. But you will need to change a key with the human that will read. A key, means any word to mix the numbers.
Upvotes: 2