플밍_ASP
classic asp) 한글, utf-8, base64 인코딩/디코딩
잠수콩
2021. 3. 24. 14:16
온갖 웹사이트 다 검색하여 한글, base64 decode 에 대한 걸 찾다찾다 참조하여 만듦.
여러 소스들도 보면, 자체 인코딩/디코딩하여 쓰면 다 사용가능하지만, 만약 다른 서버나 플랫폼에서 만든 base64로 하면 디코딩이 안되는 현상 발견.
외부에서 생성된 base64도 동일한 값을 내기 위해, 위 클래스.함수를 사용하면 정확히 일치하는 decode 내용을 볼 수 있음.
파일 :
<%
Class CryptBase64_hangul
Public Function Base64Encode(sText)
Dim oXML, oNode
Set oXML = CreateObject("Msxml2.DOMDocument.3.0")
Set oNode = oXML.CreateElement("base64")
oNode.dataType = "bin.base64"
oNode.nodeTypedValue = Stream_StringToBinary(sText)
Base64Encode = oNode.text
Set oNode = Nothing
Set oXML = Nothing
End Function
Public Function Base64Decode(ByVal vCode)
Dim oXML, oNode
Set oXML = CreateObject("Msxml2.DOMDocument.3.0")
Set oNode = oXML.CreateElement("base64")
oNode.dataType = "bin.base64"
oNode.text = vCode
Base64Decode = Stream_BinaryToString(oNode.nodeTypedValue)
Set oNode = Nothing
Set oXML = Nothing
End Function
Private Function Stream_StringToBinary(sText)
Const adTypeText = 2
Const adTypeBinary = 1
Dim BinaryStream 'As New Stream
Set BinaryStream = CreateObject("ADODB.Stream")
BinaryStream.Type = adTypeText
BinaryStream.CharSet = "utf-8"
BinaryStream.Open
BinaryStream.WriteText sText
BinaryStream.Position = 0
BinaryStream.Type = adTypeBinary
Stream_StringToBinary = BinaryStream.Read
Set BinaryStream = Nothing
End Function
Private Function Stream_BinaryToString(sBinary)
Const adTypeText = 2
Const adTypeBinary = 1
Dim BinaryStream 'As New Stream
Set BinaryStream = CreateObject("ADODB.Stream")
BinaryStream.Type = adTypeBinary
BinaryStream.Open
BinaryStream.Write sBinary
BinaryStream.Position = 0
BinaryStream.Type = adTypeText
BinaryStream.CharSet = "utf-8"
Stream_BinaryToString = BinaryStream.ReadText
Set BinaryStream = Nothing
End Function
End Class
%>
한글 포함한 문자열의 base64 encode/decode 방법 예제
Set Crypt = New CryptBase64_hangul
test = "도"
Response.write Crypt.Base64Encode(test) & "<Br>"
Response.write Replace(Crypt.Base64Encode(test), "77u/", "") & "<Br>"
Response.write Crypt.Base64Decode(Replace(Crypt.Base64Encode(test), "77u/", "")) & "<Br>"
Response.write Crypt.Base64Decode(Crypt.Base64Encode(test)) & "<Br>"
Response.write Crypt.Base64Decode("7JW8c2hoc2pha2HjhLHjhYzquJvjhLHjhYfjhYhefibDlyorPiZ+PsO34piGJic7Oy0sOg==") & "<Br>" ' 야shhsjakaㄱㅌ긛ㄱㅇㅈ^~&×*+>&~>÷☆&';;-,:
Response.write Crypt.Base64Decode("64+E64+E542o6K6A") & "<Br>" '도도獨讀
Response.write Crypt.Base64Decode("7JW8") & "<Br>"
한글, utf-8 을 base64로 인코딩하게 되면 앞에 77u/ 가 붙는다.
이것은 utf-8 로 인코딩되었다는 접두어로, 상관없이 사용가능하다.
또한,
base64로 인코딩된 문자열을 받은 후, json 에 값을 넘기려면 반드시 replace를 해야하는데.
/, ', ", 개행문자 등을 아래와 같이 변환해야한다.
Msg = Replace(Msg, "\", "\\")
Msg = Replace(Msg, "'", "\'")
Msg = Replace(Msg, """", "\""")
Msg = Replace(Msg, chr(13)&chr(10), "\n")
Msg = Replace(Msg, chr(13), "\n")
Msg = Replace(Msg, chr(10), "\n")
실제 base64 encode/decode 테스트용 사이트