我必须从增量号码(1到50000)和密码密码开始构建50,000个代码。我必须在php中完成它,最终代码必须是8或12个字符长,并且只包含大写字母(A-Z)和数字(0-9)。
最终代码必须是可解密,并带有密码...
我正在尝试使用openssl_encrypt,但我找不到一种方法来缩短最终代码。
$longCode = openssl_encrypt($number, $method, ENC_KEY, true, $iv);
$shortCode = .....
一些想法?
答案 0 :(得分:1)
第一步是使用块大小为8字节的密码方法,例如, “RC2-CBC的”。
$nr = 1234;
$key = 'secretkey';
$method = 'rc2-cbc';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$code = openssl_encrypt($nr, $method, $key, true, $iv);
第二步是将结果字符串转换为字母表;因为你的字母大小只有36,最接近和“简单”的转换是base32;这给了(在剥去可选填充之后)一串正好13个字符的字符串。
理论上,您可以将4个字节转换为base36的6个字符:
log(36) / log(2) ~ 5.17 bits, saves 1 bit after 6 blocks
6 x 5.17 ~ 31.02, 6 blocks fits inside 32 bits (unsigned long)
32 bits = 4 bytes -> 6 characters
执行错误
以下代码应该这样做 - 但不(始终)工作!
$final = '';
foreach (str_split($code, 4) as $part) {
$x = current(unpack('L', $part));
$final .= strtoupper(base_convert($x, 10, 36));
}
解码会像这样:
$code2 = '';
foreach (str_split($final, 6) as $part) {
$code2 .= pack('L', base_convert(strtolower($part), 36, 10));
}
不知何故,整数精度无法处理它,或者我正在做一些愚蠢的事情;不管怎样,它并不总是有效。
答案 1 :(得分:0)
试试这个:
// generate random ID
function generateRandomID ($len) {
//To Pull Unique Random Values Out Of AlphaNumeric
//removed number 0, capital o, number 1 and small L
//Total: keys = 32, elements = 33
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9");
//make an "empty container" or array for our keys
$keys = array();
//first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
while(count($keys) < $len) {
//"0" because we use this to FIND ARRAY KEYS which has a 0 value
//"-1" because were only concerned of number of keys which is 32 not 33
//count($characters) = 33
$x = mt_rand(0, count($characters)-1);
if(!in_array($x, $keys)) {
$keys[] = $x;
}
}
foreach($keys as $key){
$random_chars .= $characters[$key];
}
return $random_chars;
}
编辑:删除了一些字母和数字以便用户更友好地阅读,请参阅代码中的注释。