Re: Encrypt a number
Angelo Chen wrote:
On Mar 25, 9:35 am, Arne Vajh?j <a...@vajhoej.dk> wrote:
angelochen...@gmail.com wrote:
I'm looking for a way to encrypt a number into an alpha string, the
result should be:
1) reversible
2) same or less size of the original, say: given 123456789, result
might be: asbQqzW
Any idea how to achieve this?
How secure should it be ?
A lot of the standard encryption algorithms may increase
size due to rounding length up to multipla of block size.
If obfuscation is good enough then:
public static String enc(String s) {
return Integer.toString(Integer.parseInt(s, 10), 36);
}
public static String dec(String s) {
return Integer.toString(Integer.parseInt(s, 36), 10);
}
> Thanks, this meets my need, but is there a way that I can specify a
> table, say,
> 0123456789abcdefghijklmnpqrstuvwxyzWXYZ
See below for some quickly written code.
Arne
===================================
private static String DIGITS =
"0123456789abcdefghijklmnpqrstuvwxyzWXYZ";
private static int fromAny(String s, int radix) {
int res = 0;
char[] sa = s.toCharArray();
int sign = 1;
for (int i = 0; i < s.length(); i++) {
if(sa[i] != '-') {
res = res * radix + DIGITS.indexOf(sa[i]);
} else {
sign = -1;
}
}
return sign * res;
}
private static String toAny(int i, int radix) {
if(i >= 0) {
String res = "";
int tmp = i;
while (tmp > 0) {
res = DIGITS.toCharArray()[tmp % radix] + res;
tmp = tmp / radix;
}
return res;
} else {
return "-" + toAny(-i, radix);
}
}
public static String enc(String s) {
return toAny(fromAny(s, 10), 36);
}
public static String dec(String s) {
return toAny(fromAny(s, 36), 10);
}