漫游的备忘录
ASP十进制数与自定义进制的转换程序
2012-8-18 漫游
'本程序是用于将正整数与6位字串互相转换,可以应用于UserID、数据库自增ID的转换,转换后看来比较难以捉摸,增强安全性,也可以一定程度的提高他人采集难度,不过也让程序更加复杂化了

'本例用62位长的字串,转换后的6位数可以表示2^62即500多亿

'本程序只能对单字节的字符进行处理,另外程序中没有对字符的大小写特别区分对待,尚不知会否在特定情况下出错

server.ScriptTimeout=3



response.write BaseEncode(1)&"<br />"

response.write BaseDecode("0a9nQR")&"<br />"



Const BASE_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" '区分大小写,可以增减字符(不建议使用特殊字符或标点,可能会造成其它问题)

Const BASE_BASIC = 150000000 '基础增值,使得转换后能满位,看起来比较像样

Const BASE_PLUS = 62 '倍数,即函数的进制位数,等于BASE_CHARACTERS的长度,本例为62进制

Const BASE_LENGTH = 6 '预期字串的长度,必须符合,不能长,不能短(短的前面补零)





'加密,把给出的十进制正整数转换成目标进制数,再替换以预定字串

Function BaseEncode(ByVal asContents)

asContents = clng(asContents) + BASE_BASIC

'整除62,第1个余数作个位,第2个余数作十位……最后的商作最高位

BaseEncode = ""

do while true

temp = asContents Mod BASE_PLUS

BaseEncode = BaseNum2Str(temp) & BaseEncode

asContents = asContents - temp

asContents = asContents / BASE_PLUS

if asContents < BASE_PLUS then

BaseEncode = BaseNum2Str(asContents) & BaseEncode

exit do

end if

loop

'补零,注意不一定是补“0”这个字符

do while true

if len(BaseEncode) < BASE_LENGTH then

BaseEncode = left(BASE_CHARACTERS,1) & BaseEncode

else

exit do

end if

loop

End Function



'本进制转为十进制,只处理一个位

function BaseStr2Num(temp)

temp = left(cstr(temp),1)

BaseStr2Num = InStr(BASE_CHARACTERS, temp) - 1

end function



'解密,把给出的字串还原为目标进制数,再转为十进制正整数(注意大小写,可用ASC)

Function BaseDecode(ByVal asContents)

asContents = StrReverse(cstr(asContents))

for temp = 1 to len(asContents)

BaseDecode = BaseDecode + BaseStr2Num(mid(asContents,temp)) * BASE_PLUS ^ (temp-1)

next

BaseDecode = BaseDecode - BASE_BASIC


End Function



'十进制转为本进制,只处理一个位

function BaseNum2Str(temp)

if isnumeric(temp) then

if temp>=0 and temp<=BASE_PLUS then

BaseNum2Str = mid(BASE_CHARACTERS,temp+1,1)

else

BaseNum2Str = 0

end if

else

BaseNum2Str = 0

end if

end function