由于要传一个需要保密的ID,因此用到对称加密,但mcrypt_encrypt算法加密后字符串太长,因此想实现一个自定义加密算法,想法如下
首先先对key计算sha1,取结果的前32bit,然后跟要加密整数进行异或,得到一个加密后的32bit结果
对结果分组:2bit | 6bit | 6bit | 6bit | 6bit | 6bit
各个组分别取名为:a0、a1、a2、a3、a4、a5
另定义一个长度64的字典数组
$dict=array('1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'01','02','03');
将前面每个分组的值作为字典数组的下标,则加密结果为:$dict[a0].$dict[a1].$dict[a2].$dict[a3].$dict[a4].$dict[a5]
这样加密后的结果就是一个长度6-12的字符串,如果字典数组最后3个元素用其他单字符表示,那么结果就固定为6个字符的字符串。
由于初学php不久,对php的函数库不熟悉,求大侠帮忙实现下加密解密算法:
string encrypt(int id,string key)
int decrypt(string text,string key)
------解决方案--------------------
------解决方案--------------------
学习了,厉害。
------解决方案--------------------
这个够乱的了吧
$id = 1234;
$key = 'aaa';
for($i=1; $i<100; $i++) {
printf("%-10d %s %s\n", $id, $s = encrypt($id++, $key), decrypt( $s, $key));
}
function encrypt($id, $key) {
$dict = array('1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'-','=','*'
);
$n = rand(0, 15);
srand($n);
$key = current(unpack('L', substr(sha1($key, 1), $n)));
$id ^= $key;
$t = str_split(sprintf('%04b%032b', $n, $id), 6);
foreach($t as $i=>&$v) {
$v = $dict[bindec($v)];
if($i == 0) shuffle($dict);
}
return join($t);
}
function decrypt($s, $key) {
$dict = array('1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'-','=','*'
);
$m = array_search($s{0}, $dict);
$n = $m >> 2;
srand($n);
shuffle($dict);
$dict = array_flip($dict);
foreach(str_split($s) as $i=>$c) {
$r[] = sprintf('%06b', $i==0 ? $m&0x03 : $dict[$c]);
}
$id = bindec(join($r));
$key = current(unpack('L', substr(sha1($key, 1), $n)));
return $id ^ $key;
}
1234 4rHK4B 1234
1235 oD2LN* 1235
1236 wqkf8u 1236
1237 6k=GVU 1237
1238 bxeCr* 1238
1239 =W-AOi 1239
1240 IiQ3e1 1240
1241 z6uMMA 1241
1242 WLcnd8 1242
1243 Rizj*M 1243
1244 4rHK47 1244
1245 oD2LNT 1245
1246 wqkf8Z 1246
1247 6k=GVJ 1247
1248 bxeCrE 1248
1249 =W-AOP 1249
1250 IiQ3et 1250
1251 z6uMMP 1251
1252 WLcndU 1252
1253 Rizj*p 1253
1254 4rHK4s 1254
1255 oD2LNs 1255
1256 wqkf84 1256
1257 6k=GVn 1257
1258 bxeCrL 1258
1259 =W-AOT 1259
1260 IiQ3ex 1260
1261 z6uMM1 1261
1262 WLcndD 1262
1263 Rizj*s 1263
1264 4rHK4h 1264
1265 oD2LNq 1265
1266 wqkf83 1266