[英]Encrypt random 6 digit number -> human readable
我們有1到999999之間的數字,我們需要使用簡單的算法進行加密。 加密的輸出應該是人類可讀的字符(AZ,0-9),並且不得超過6位數字。
是否可以使用簡單的算法將數字123456加密為GH6ZT3,然后再將GH6ZT3解密為123456?
我只能找到使用Base32或Base64加密的示例,但是加密輸出遠大於6位數字:-(
如果您只是想混淆這些數字,則可以通過組合使用模塊化算術和基數為36的字符串來輕松實現。
這里有幾個函數可以使用0到(36 6 − 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;
}
但是請記住,混淆后的字符串將包含每個6個字母或更少的單詞。 包括所有四個字母的單詞 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.