Classic ASP Base64 編碼 解碼

  • 1809
  • 0

Classic ASP 中  對 Unicode 字串 進行 Base64 編碼及解碼

因工作上需要在 ASP 對Base64字串解碼
所以有了這篇

Function EncodeToBase64(strSource)
result = ""
totalBytesCount = GetBytesCount(strSource)
do while(totalBytesCount > 0)
	tempStr = LeftB(strSource, 3)
	tempBytesCount = GetBytesCount(tempStr)
	totalBytesCount = totalBytesCount - tempBytesCount
	strSource = RightB(strSource , totalBytesCount)
	redim bitArray(24)
	for i = 0 to tempBytesCount - 1
		byteValue = AscB(MidB(tempStr,i+1,1))
		for j = 0 to 7
			bitArray(i*8+j) = (byteValue And (2^(7-j))) / (2^(7-j))
		next
	next
	for i = 0 to UBound(bitArray) - 1 - (3-tempBytesCount) * 8 step 6
		byteValue = 0
		for j = 0 to 5
			byteValue = byteValue + bitArray(i+j) * (2^(5-j))
		next
		result = result & Mid(Base64Chars, byteValue+1, 1)
	next
	for i = 1 to (3-tempBytesCount)
		result = result & "="
	next
loop
EncodeToBase64 = result
End Function

'http://blog.darkthread.net/post-2006-08-29-kb-lenb.aspx
Function GetBytesCount(str)
	count=0
	for i = 1 to LenB(str)
		asciiValue = AscB(MidB(str,i,1))
		if (asciiValue > 255) or (asciiValue < 0) then
			count=count+2
		else
			count=count+1
		end if
	next
	GetBytesCount = count
end function

Function DecodeFromBase64(strSource)
result = ""
do while(strSource <> "")
	tempStr = Left(strSource, 4)
	strSource = Right(strSource , Len(strSource)-Len(tempStr))
	redim bitArray(24)
	eqCount= 0
	for i = 0 to Len(tempStr) - 1
		ch = Mid(tempStr,i+1,1)
		if ch = "=" then
			eqCount = eqCount + 1
			byteValue = -1
		else
			byteValue = InStr(Base64Chars, ch) - 1
		end if
		if byteValue >= 0 then
			for j = 0 to 5
				bitArray( i * 6 + j) = (byteValue And 2^(5-j)) / 2^(5-j)
			next
		end if
	next
	for i = 0 to UBound(bitArray) - 1 step 8
		byteValue = 0
		for j = 0 to 7
			byteValue = byteValue + bitArray(i+j) * 2^(7-j)
		next
		result = result & ChrB(byteValue)
	next
loop
DecodeFromBase64 = result
End Function

測試程式:

<%
expectedEncoded = "LG5mijEAMgAzADGKn1LLhA==" '從C#利用 Convert.ToBase64String 取得
strSource = "測試123許功蓋"

Response.AddHeader "Content-Type", "text/xml;charset=UTF-8"
Response.Write "<?xml version=""1.0"" encoding=""utf-8""?>"
Response.Write "<TestResult origin=""" & strSource & """>"
strEncoded = EncodeToBase64(strSource)
Response.Write "<Encoded>" & strEncoded & "</Encoded>"
Response.Write "<SameWithCSharp>" & (expectedEncoded = strEncoded) & "</SameWithCSharp>"
strDecoded = DecodeFromBase64(strEncoded)
Response.Write "<Decoded>" & strDecoded
Response.Write "</Decoded></TestResult>"
%>

測試結果:

參考資料:

  1.  Base64 - wiki
  2.  KB-不可信的LENB函數