'디코딩'에 해당되는 글 1

  1. 2008.10.02 [ASP] Base64 인코딩 관련 모음.
IT_Expert/WebProgramming | Posted by 낫기법필 2008. 10. 2. 13:27

[ASP] Base64 인코딩 관련 모음.

정리는 하지 않고 모으기만 했다.
정리를 해야 하는데 시간이 현재 없으므로 일단 모아놓기만 하자..


0. ///////////////////////////////////////////////////////////////////////
0. 컴포넌트 방식
0. ///////////////////////////////////////////////////////////////////////
http://sevillaonline.com/ActiveX/Base64.htm



1. ///////////////////////////////////////////////////////////////////////
1. ///////////////////////////////////////////////////////////////////////


Option Explicit

Dim sBASE_64_CHARACTERS, sBASE_64_CHARACTERSansi
sBASE_64_CHARACTERS        = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
sBASE_64_CHARACTERSansi    = strUnicode2Ansi(sBASE_64_CHARACTERS)


Function strUnicodeLen(asContents)
    Dim asContents1    : asContents1 ="a"    & asContents
    Dim Len1        : Len1=Len(asContents1)
    Dim K        : K=0
    Dim I, Asc1

    For I=1 To Len1
        Asc1    = asc(mid(asContents1,I,1))
        IF Asc1 < 0 Then Asc1    = 65536 + Asc1
        IF Asc1 > 255 Then
            K    = K + 2
        ELSE
            K    = K + 1
        End IF
    Next

    strUnicodeLen = K - 1
End Function

Function strUnicode2Ansi(asContents)
    Dim Len1            : Len1 = Len(asContents)
    Dim I, VarCHAR, VarASC, VarHEX, VarLOW, VarHIGH

    strUnicode2Ansi    = ""

    For I = 1 to Len1
        VarCHAR    = Mid(asContents,I,1)
        VarASC    = Asc(VarCHAR)
        IF VarASC < 0 Then VarASC = VarASC + 65536
        IF VarASC > 255 Then
            VarHEX        = Hex(VarASC)
            VarLOW        = Left(VarHEX,2)
            VarHIGH        = Right(VarHEX,2)
            strUnicode2Ansi    = strUnicode2Ansi & ChrB("&H" & VarLOW ) & ChrB("&H" & VarHIGH )
        Else
            strUnicode2Ansi    = strUnicode2Ansi & ChrB(VarASC)
        End IF
    Next
End Function


Function strAnsi2Unicode(asContents)
    Dim Len1            : Len1        = LenB(asContents)
    Dim VarCHAR, VarASC, I

    strAnsi2Unicode    = ""

    IF Len1=0 Then    Exit Function

    For I=1 To Len1
        VarCHAR    = MidB(asContents,I,1)
        VarASC    = AscB(VarCHAR)
        IF VarASC > 127 Then
            strAnsi2Unicode    = strAnsi2Unicode & Chr(AscW(MidB(asContents, I+1,1) & VarCHAR))
            I        = I + 1
        Else
            strAnsi2Unicode    = strAnsi2Unicode & Chr(VarASC)
        End IF
    Next

End function

Function Base64encode(asContents)
    Dim lnPosition
    Dim lsResult
    Dim Char1
    Dim Char2
    Dim Char3
    Dim Char4
    Dim Byte1
    Dim Byte2
    Dim Byte3
    Dim SaveBits1
    Dim SaveBits2
    Dim lsGroupBinary
    Dim lsGroup64
    Dim M3, M4, Len1, Len2

    Len1            =LenB(asContents)

    IF Len1 < 1 Then
        Base64encode    = ""
        Exit Function
    End IF

    M3=Len1 Mod 3

    IF M3 > 0 Then asContents = asContents & String(3 - M3, ChrB(0))

    IF m3 > 0 Then
        Len1    = Len1 + (3 - M3)
        Len2    = Len1 - 3
    Else
        Len2    = Len1
    End IF

    lsResult    = ""

    For lnPosition = 1 To Len2 Step 3
        lsGroup64    = ""
        lsGroupBinary    = MidB(asContents, lnPosition, 3)

        Byte1        = AscB(MidB(lsGroupBinary, 1, 1))    : SaveBits1    = Byte1 And 3
        Byte2        = AscB(MidB(lsGroupBinary, 2, 1))    : SaveBits2    = Byte2 And 15
        Byte3        = AscB(MidB(lsGroupBinary, 3, 1))

        Char1        = MidB(sBASE_64_CHARACTERSansi, ((Byte1 And 252) \ 4) + 1, 1)
        Char2        = MidB(sBASE_64_CHARACTERSansi, (((Byte2 And 240) \ 16) Or (SaveBits1 * 16) And &HFF) + 1, 1)
        Char3        = MidB(sBASE_64_CHARACTERSansi, (((Byte3 And 192) \ 64) Or (SaveBits2 * 4) And &HFF) + 1, 1)
        Char4        = MidB(sBASE_64_CHARACTERSansi, (Byte3 And 63) + 1, 1)
        lsGroup64    = Char1 & Char2 & Char3 & Char4

        lsResult        = lsResult & lsGroup64
    Next

    IF M3 > 0 Then
        lsGroup64    = ""
        lsGroupBinary    = MidB(asContents, Len2 + 1, 3)

        Byte1        = AscB(MidB(lsGroupBinary, 1, 1))    : SaveBits1    = Byte1 And 3
        Byte2        = AscB(MidB(lsGroupBinary, 2, 1))    : SaveBits2    = Byte2 And 15
        Byte3        = AscB(MidB(lsGroupBinary, 3, 1))

        Char1        = MidB(sBASE_64_CHARACTERSansi, ((Byte1 And 252) \ 4) + 1, 1)
        Char2        = MidB(sBASE_64_CHARACTERSansi, (((Byte2 And 240) \ 16) Or (SaveBits1 * 16) And &HFF) + 1, 1)
        Char3        = MidB(sBASE_64_CHARACTERSansi, (((Byte3 And 192) \ 64) Or (SaveBits2 * 4) And &HFF) + 1, 1)

        IF M3=1 Then
            lsGroup64    = Char1 & Char2 & ChrB(61) & ChrB(61)
        Else
            lsGroup64    = Char1 & Char2 & Char3 & ChrB(61)
        End IF

        lsResult        = lsResult & lsGroup64
    End IF

    Base64encode = lsResult
End Function

Function Base64decode(asContents)
    Dim lsResult
    Dim lnPosition
    Dim lsGroup64, lsGroupBinary
    Dim Char1, Char2, Char3, Char4
    Dim Byte1, Byte2, Byte3
    Dim M4, Len1, Len2

    Len1    = LenB(asContents)
    M4    = Len1 Mod 4

    IF Len1 < 1 Or M4 > 0 Then
        Base64decode = ""
        Exit Function
    End IF

    IF MidB(asContents, Len1, 1) = ChrB(61) Then    M4 = 3
    IF MidB(asContents, Len1-1, 1) = ChrB(61) Then    M4 = 2

    IF M4 = 0 Then
        Len2    = Len1
    Else
        Len2    = Len1 - 4
    End IF

    For lnPosition = 1 To Len2 Step 4
        lsGroupBinary    = ""
        lsGroup64    = MidB(asContents, lnPosition, 4)

        Char1        = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 1, 1)) - 1
        Char2        = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 2, 1)) - 1
        Char3        = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 3, 1)) - 1
        Char4        = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 4, 1)) - 1

        Byte1        = ChrB(((Char2 And 48) \ 16) Or (Char1 * 4) And &HFF)
        Byte2        = lsGroupBinary & ChrB(((Char3 And 60) \ 4) Or (Char2 * 16) And &HFF)
        Byte3        = ChrB((((Char3 And 3) * 64) And &HFF) Or (Char4 And 63))
        lsGroupBinary    = Byte1 & Byte2 & Byte3

        lsResult        = lsResult & lsGroupBinary
    Next

    IF M4 > 0 Then
        lsGroupBinary    = ""
        lsGroup64    = MidB(asContents, Len2 + 1, M4) & ChrB(65)
        IF M4=2 Then
            lsGroup64    = lsGroup64 & chrB(65)
        End IF
        Char1    = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 1, 1)) - 1
        Char2    = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 2, 1)) - 1
        Char3    = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 3, 1)) - 1
        Char4    = InStrB(sBASE_64_CHARACTERSansi, MidB(lsGroup64, 4, 1)) - 1

        Byte1    = ChrB(((Char2 And 48) \ 16) Or (Char1 * 4) And &HFF)
        Byte2    = lsGroupBinary & ChrB(((Char3 And 60) \ 4) Or (Char2 * 16) And &HFF)
        Byte3    = ChrB((((Char3 And 3) * 64) And &HFF) Or (Char4 And 63))

        IF M4=2 Then
            lsGroupBinary    = Byte1
        elseIF M4=3 Then
            lsGroupBinary    = Byte1 & Byte2
        end IF

        lsResult            = lsResult & lsGroupBinary
    End IF

    Base64decode            = lsResult
End Function


'################################## 사용 샘플 ##################################
Dim ORIGNvalue    : ORIGNvalue    = "하완어환오라ㅓ고ㅓ엉ㅁㄹ22ㅁㅁ@@ㅇㅁㄹ;ㄴㅇaabcsdfaeerdfadf"
Dim EncodeA    : EncodeA        = strAnsi2Unicode(Base64encode(strUnicode2Ansi(ORIGNvalue)))
Dim DecodeA    : DecodeA    = strAnsi2Unicode(Base64decode(strUnicode2Ansi(EncodeA)))

response.write "------------------------------------------------------------------------<br />"
response.write "lsResult : " & ORIGNvalue            & "<br />"
response.write "lsResult : " & EncodeA                & "<br />"
response.write "lsResult : " & DecodeA                & "<br />"
response.write "------------------------------------------------------------------------<br />"


[출처] base64 인코드, 디코드 - asp용 |작성자 여유
[펌] http://databook.tistory.com/tag/Base64



2. ///////////////////////////////////////////////////////////////////////
2. ///////////////////////////////////////////////////////////////////////

            '/////////////////////////////////////////////////
            '/// 어떤분이 외국소스에서 구해 인터넷에 올려놓은 소스입니다.
            '/// 쿠키에 많이 사용하더군요.
            '/////////////////////////////////////////////////


            OPTION EXPLICIT
            const BASE_64_MAP_INIT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            dim nl
            ' zero based arrays
            dim Base64EncMap(63)
            dim Base64DecMap(127)

            '/////////////////////////////////////////////////
            '/// must be called before using anything else
            '/// 다른 작업이전에 먼저 호출해야하는 함수입니다.
            '/////////////////////////////////////////////////
            PUBLIC SUB initCodecs()
                        ' init vars
                        nl = "<P>" & chr(13) & chr(10)
                        ' setup base 64
                        dim max, idx
                                    max = len(BASE_64_MAP_INIT)
                        for idx = 0 to max - 1
                                    ' one based string
                                    Base64EncMap(idx) = mid(BASE_64_MAP_INIT, idx + 1, 1)
                        next
                        for idx = 0 to max - 1
                                    Base64DecMap(ASC(Base64EncMap(idx))) = idx
                        next
            END SUB


            '/////////////////////////////////////////////////
            '/// encode base 64 encoded string
            '/// Base64로 인코딩하는 함수입니다.
            '/////////////////////////////////////////////////
            PUBLIC FUNCTION base64Encode(plain)

                        if len(plain) = 0 then
                                    base64Encode = ""
                                    exit function
                        end if

                        dim ret, ndx, by3, first, second, third
                        by3 = (len(plain) \ 3) * 3
                        ndx = 1
                        do while ndx <= by3
                                    first  = asc(mid(plain, ndx+0, 1))
                                    second = asc(mid(plain, ndx+1, 1))
                                    third  = asc(mid(plain, ndx+2, 1))
                                    ret = ret & Base64EncMap(  (first \ 4) AND 63 )
                                    ret = ret & Base64EncMap( ((first * 16) AND 48) + ((second \ 16) AND 15 ) )
                                    ret = ret & Base64EncMap( ((second * 4) AND 60) + ((third \ 64) AND 3 ) )
                                    ret = ret & Base64EncMap( third AND 63)
                                    ndx = ndx + 3
                        loop
                        ' check for stragglers
                        if by3 < len(plain) then
                                    first  = asc(mid(plain, ndx+0, 1))
                                    ret = ret & Base64EncMap(  (first \ 4) AND 63 )
                                    if (len(plain) MOD 3 ) = 2 then
                                                second = asc(mid(plain, ndx+1, 1))
                                                ret = ret & Base64EncMap( ((first * 16) AND 48) + ((second \ 16) AND 15 ) )
                                                ret = ret & Base64EncMap( ((second * 4) AND 60) )
                                    else
                                                ret = ret & Base64EncMap( (first * 16) AND 48)
                                                ret = ret & "="
                                    end if
                                    ret = ret & "="
                        end if

                        base64Encode = ret
            END FUNCTION


            '/////////////////////////////////////////////////
            '/// decode base 64 encoded string
            '/// Base64로 디코딩하는 함수 입니다.
            '/////////////////////////////////////////////////
            PUBLIC FUNCTION base64Decode(scrambled)

                        if len(scrambled) = 0 then
                                    base64Decode = ""
                                    exit function
                        end if

                        ' ignore padding
                        dim realLen
                        realLen = len(scrambled)
                        do while mid(scrambled, realLen, 1) = "="
                                    realLen = realLen - 1
                        loop
                        dim ret, ndx, by4, first, second, third, fourth
                        ret = ""
                        by4 = (realLen \ 4) * 4
                        ndx = 1
                        do while ndx <= by4
                                    first  = Base64DecMap(asc(mid(scrambled, ndx+0, 1)))
                                    second = Base64DecMap(asc(mid(scrambled, ndx+1, 1)))
                                    third  = Base64DecMap(asc(mid(scrambled, ndx+2, 1)))
                                    fourth = Base64DecMap(asc(mid(scrambled, ndx+3, 1)))
                                    ret = ret & chr( ((first * 4) AND 255) +  ((second \ 16) AND 3))
                                    ret = ret & chr( ((second * 16) AND 255) + ((third \ 4) AND 15) )
                                    ret = ret & chr( ((third * 64) AND 255) +  (fourth AND 63) )
                                    ndx = ndx + 4
                        loop
                        ' check for stragglers, will be 2 or 3 characters
                        if ndx < realLen then
                                    first  = Base64DecMap(asc(mid(scrambled, ndx+0, 1)))
                                    second = Base64DecMap(asc(mid(scrambled, ndx+1, 1)))
                                    ret = ret & chr( ((first * 4) AND 255) +  ((second \ 16) AND 3))
                                    if realLen MOD 4 = 3 then
                                                third = Base64DecMap(asc(mid(scrambled,ndx+2,1)))
                                                ret = ret & chr( ((second * 16) AND 255) + ((third \ 4) AND 15) )
                                    end if
                        end if

                        base64Decode = ret
    END FUNCTION


            '/////////////////////////////////////////////////
            '/// initialize
            '/// 초기화
            '/////////////////////////////////////////////////
            call initCodecs

            '/////////////////////////////////////////////////
            '/// Testing code
            '/// 테스트 코딩
            '/////////////////////////////////////////////////
            '    dim inp, encode
            '    inp = request.QueryString("input")
            '    encode = base64Encode(inp)
            '    response.write "Encoded value = " & encode & nl
            '    response.write "Decoded value = " & base64Decode(encode) & nl

[펌] http://duraboys.tistory.com/229


3. ///////////////////////////////////////////////////////////////////////
3. ///////////////////////////////////////////////////////////////////////
데브피아에서 퍼왔던것 같다...-_-;

메모되어있는 내용을 적는다.


사용해보니 문제점이 있다.

한글을 이용해서 PHP와 연동이 안된다.

영어로는 PHP 연동이 잘되는것을 확인하였음..-0-;



Const sBASE_64_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
'Const sBASE_64_CHARACTERS = "9876543210+\qwertyuiopasdfghjklzxcvbnmPOIUYTREWQLKJHGFDSAMNBVCXZ"


Function Base64decode(ByVal asContents)
Dim lsResult
Dim lnPosition
Dim lsGroup64, lsGroupBinary
Dim Char1, Char2, Char3, Char4
Dim Byte1, Byte2, Byte3
If Len(asContents) Mod 4 > 0 Then asContents = asContents & String(4 - (Len(asContents) Mod 4), " ")
lsResult = ""

For lnPosition = 1 To Len(asContents) Step 4
    lsGroupBinary = ""
    lsGroup64 = Mid(asContents, lnPosition, 4)
    Char1 = InStr(sBASE_64_CHARACTERS, Mid(lsGroup64, 1, 1)) - 3
    Char2 = InStr(sBASE_64_CHARACTERS, Mid(lsGroup64, 2, 1)) - 3
    Char3 = InStr(sBASE_64_CHARACTERS, Mid(lsGroup64, 3, 1)) - 3
    Char4 = InStr(sBASE_64_CHARACTERS, Mid(lsGroup64, 4, 1)) - 3
    Byte1 = Chr(((Char2 And 48) \ 16) Or (Char1 * 4) And &HFF)
    Byte2 = lsGroupBinary & Chr(((Char3 And 60) \ 4) Or (Char2 * 16) And &HFF)
    Byte3 = Chr((((Char3 And 3) * 64) And &HFF) Or (Char4 And 63))
    lsGroupBinary = Byte1 & Byte2 & Byte3

    lsResult = lsResult + lsGroupBinary
Next
Base64decode = lsResult
End Function

Function Base64encode(ByVal asContents)
Dim lnPosition
Dim lsResult
Dim Char1
Dim Char2
Dim Char3
Dim Char4
Dim Byte1
Dim Byte2
Dim Byte3
Dim SaveBits1
Dim SaveBits2
Dim lsGroupBinary
Dim lsGroup64

If Len(asContents) Mod 3 > 0 Then asContents = asContents & String(3 - (Len(asContents) Mod 3), " ")
lsResult = ""

For lnPosition = 1 To Len(asContents) Step 3
    lsGroup64 = ""
    lsGroupBinary = Mid(asContents, lnPosition, 3)

    Byte1 = Asc(Mid(lsGroupBinary, 1, 1)): SaveBits1 = Byte1 And 3
    Byte2 = Asc(Mid(lsGroupBinary, 2, 1)): SaveBits2 = Byte2 And 15
    Byte3 = Asc(Mid(lsGroupBinary, 3, 1))

    Char1 = Mid(sBASE_64_CHARACTERS, ((Byte1 And 252) \ 4) + 3, 1)
    Char2 = Mid(sBASE_64_CHARACTERS, (((Byte2 And 240) \ 16) Or (SaveBits1 * 16) And &HFF) + 3, 1)
    Char3 = Mid(sBASE_64_CHARACTERS, (((Byte3 And 192) \ 64) Or (SaveBits2 * 4) And &HFF) + 3, 1)
    Char4 = Mid(sBASE_64_CHARACTERS, (Byte3 And 63) + 3, 1)
    lsGroup64 = Char1 & Char2 & Char3 & Char4

    lsResult = lsResult + lsGroup64
Next

Base64encode = lsResult
End Function
[출처] ASP BASE64로 인코딩 디코딩|작성자 마루



4. ///////////////////////////////////////////////////////////////////////
4. ///////////////////////////////////////////////////////////////////////
출처:http://cafe.naver.com/aspman

==========================================================

getB64Decode

==========================================================

설명


getB64Encode()로 인코딩된 문자열을 원 문자열로 디코딩해줍니다.

대부분의 특징은 getB64Encode()와 같구요.

주요점은 Base64Chars 문자열을 getB64Encode()와 같은걸 써야 한다는 겁니다.

당연한것이 그래야 디코딩이 정상적으로 되겠죠.

그리고 이 함수는 getB64Encode()에서도 설명했지만 한글을 인코딩 한 문자열을

정상적으로 디코딩하지 못합니다. 그러므로 숫자, 영문을 암호화할때만 사용하세요.


==========================================================

인자

base64DeString : Base64로 인코딩된 문자열


==========================================================

반환값

원 문자열.


==========================================================

함수소스


 Public Function getB64Decode(ByVal base64DeString)
        'rfc1521

        Dim dataLength, sOut, groupBegin
        Const Base64Chars= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"


            'remove white spaces, If any
            base64DeString = Replace(base64DeString, vbCrLf, "")
            base64DeString = Replace(base64DeString, vbTab, "")
            base64DeString = Replace(base64DeString, " ", "")

            'The source must consists from groups with Len of 4 chars
            dataLength = Len(base64DeString)
            If dataLength Mod 4 <> 0 Then
                Err.Raise(1, "Base64Decode", "Bad Base64 string.")
                Exit Function
            End If


            ' Now decode each group:
            For groupBegin = 1 To dataLength Step 4
                Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
                ' Each data group encodes up To 3 actual bytes.
                numDataBytes = 3
                nGroup = 0

                For CharCounter = 0 To 3
                    ' Convert each character into 6 bits of data, And add it To
                    ' an integer For temporary storage.  If a character is a '=', there
                    ' is one fewer data byte.  (There can only be a maximum of 2 '=' In
                    ' the whole string.)

                    thisChar = Mid(base64DeString, groupBegin + CharCounter, 1)

                    If thisChar = "=" Then
                        numDataBytes = numDataBytes - 1
                        thisData = 0
                    Else
                        thisData = InStr(Base64Chars, thisChar) - 1
                    End If
                    If thisData = -1 Then
                        Err.Raise(2, "Base64Decode", "Bad character In Base64 string.")
                        Exit Function
                    End If

                    nGroup = 64 * nGroup + thisData
                Next

                'Hex splits the long To 6 groups with 4 bits
                nGroup = Hex(nGroup)

                'Add leading zeros
                nGroup = New String(CChar("0"), 6 - Len(nGroup)) & nGroup

                'Convert the 3 byte hex integer (6 chars) To 3 characters
                pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
                  Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
                  Chr(CByte("&H" & Mid(nGroup, 5, 2)))

                'add numDataBytes characters To out string
                sOut = sOut & Left(pOut, numDataBytes)
            Next


            getB64Decode = sOut


    End Function





==========================================================

getB64Encode

==========================================================

설명


스트링을 Base64 로 인코딩해주는 함수 입니다. (디코딩 함수인 getB64Decode()과 같이 사용하면 됩니다. )

짠건 아니고, 굴러다니는거 쓰고 있습니다.

이 함수의 특징은 Base64Chars에 있는 문자열의 순서를 바꾸면 로직이 같아도

전혀 다른 결과가 나온다는 겁니다.

내부적으로는 VB.NET으로 DLL화 해서 사용하고 있지만,

굳이 그렇게 하지 않더라도 Base64Chars  문자열만 노출되지 않도록

프로젝트 단위로, 혹은 오픈시점에 Base64Chars 문자열만 교체해주면 별문제 없을듯 싶습니다.

그리고 이 함수는 한글은 인코딩을 하지 못합니다. (정확히는 인코딩은 되지만 디코딩이 되지 않습니다. )

그러므로 숫자, 영문을 암호화할때만 사용하세요.

MyASC()는 getB64Encode()내부에서 사용하는 sub Function입니다.


==========================================================

인자

base64EnString : 인코딩할 문자열


==========================================================

반환값

Base64로 인코딩된 문자열.


==========================================================

함수소스


Function getB64Encode(ByVal base64EnString)

        Dim sOut

        Dim I
        Dim Newbase64EnString

        Const Base64Chars= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"


            Newbase64EnString = CStr(base64EnString)

            'For each group of 3 bytes
            For I = 1 To Len(Newbase64EnString) Step 3
                Dim nGroup, pOut, sGroup

                'Create one long from this 3 bytes.
                nGroup = &H10000 * Asc(Mid(Newbase64EnString, I, 1)) + _
                  &H100 * MyASC(Mid(Newbase64EnString, I + 1, 1)) + MyASC(Mid(Newbase64EnString, I + 2, 1))

                'Oct splits the long To 8 groups with 3 bits
                nGroup = Oct(nGroup)

                'Add leading zeros
                nGroup = New String(CChar("0"), 8 - Len(nGroup)) & nGroup

                'Convert To Base64Chars
                pOut = Mid(Base64Chars, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _
                  Mid(Base64Chars, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _
                  Mid(Base64Chars, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _
                  Mid(Base64Chars, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)

                'Add the part To OutPut string
                sOut = sOut + pOut

                'Add a new line For Each 76 chars In dest (76*3/4 = 57)
                'If (I + 2) Mod 57 = 0 Then sOut = sOut + vbCrLf
            Next
            Select Case Len(Newbase64EnString) Mod 3
                Case 1 '8 bit final
                    sOut = Left(sOut, Len(sOut) - 2) + "=="
                Case 2 '16 bit final
                    sOut = Left(sOut, Len(sOut) - 1) + "="
            End Select


            getB64Encode = sOut


    End Function


'-------------------------------------------------------------


Function MyASC(OneChar)
  If OneChar = "" Then MyASC = 0 Else MyASC = Asc(OneChar)
End Function



5. ///////////////////////////////////////////////////////////////////////
5. 자바스크립트
5. ///////////////////////////////////////////////////////////////////////
asp에서 base64 인코딩 및 디코딩 소스

ASP에서 메일을 주고 받을 때 메일 인코딩 방식인 base64를 인코딩하거나 디코딩하여야 하는데 기본적으로 제공되는 함수가 없어 간혹 곤란을 겪으셨을 것입니다.

아래 소스는 asp 페이지에서 자바스크립트를 사용하여 base64 인코딩, 디코딩을 하기 위한 함수입니다. 또한 아웃룩이나 아웃룩 익스프레스에서 사용하는 편지함 폴더를 인코딩하기 위한 IMAP_UTF7 함수를 포함하였습니다.


<script language="JavaScript">

var enc64List, dec64List;

function initBase64() {
  enc64List = new Array();
  dec64List = new Array();
  var i;
  for (i = 0; i < 26; i++) {
       enc64List[enc64List.length] = String.fromCharCode(65 + i);
  }
  for (i = 0; i < 26; i++) {
       enc64List[enc64List.length] = String.fromCharCode(97 + i);
  }
  for (i = 0; i < 10; i++) {
       enc64List[enc64List.length] = String.fromCharCode(48 + i);
  }
  enc64List[enc64List.length] = "+";
  enc64List[enc64List.length] = "/";
  for (i = 0; i < 128; i++) {
       dec64List[dec64List.length] = -1;
  }
  for (i = 0; i < 64; i++) {
       dec64List[enc64List[i].charCodeAt(0)] = i;
  }
}

function base64Encode(str) {
  var c, d, e, end = 0;
  var u, v, w, x;
  var ptr = -1;
  var input = str.split("");
  var output = "";
  while(end == 0) {
       c = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) :
           ((end = 1) ? 0 : 0);
       d = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) :
           ((end += 1) ? 0 : 0);
       e = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) :
           ((end += 1) ? 0 : 0);
       u = enc64List[c >> 2];
       v = enc64List[(0x00000003 & c) << 4 | d >> 4];
       w = enc64List[(0x0000000F & d) << 2 | e >> 6];
       x = enc64List[e & 0x0000003F];
       if (end >= 1) {x = "=";}
       if (end == 2) {w = "=";}
       if (end < 3) {output += u + v + w + x;}
  }
  var formattedOutput = "";
  var lineLength = 76;
  while (output.length > lineLength) {
    formattedOutput += output.substring(0, lineLength) + "\n";
    output = output.substring(lineLength);
  }
  formattedOutput += output;
  return formattedOutput;
}

function base64Decode(str) {
  var c=0, d=0, e=0, f=0, i=0, n=0;
  var input = str.split("");
  var output = "";
  var ptr = 0;
  do {
       f = input[ptr++].charCodeAt(0);
       i = dec64List[f];
       if ( f >= 0 && f < 128 && i != -1 ) {
           if ( n % 4 == 0 ) {
               c = i << 2;
           } else if ( n % 4 == 1 ) {
               c = c | ( i >> 4 );
               d = ( i & 0x0000000F ) << 4;
           } else if ( n % 4 == 2 ) {
               d = d | ( i >> 2 );
               e = ( i & 0x00000003 ) << 6;
           } else {
               e = e | i;
           }
           n++;
           if ( n % 4 == 0 ) {
               output += String.fromCharCode(c) +
                         String.fromCharCode(d) +
                         String.fromCharCode(e);
           }
       }
  }
  while (typeof input[ptr] != "undefined");
  output += (n % 4 == 3) ? String.fromCharCode(c) + String.fromCharCode(d) :
             ((n % 4 == 2) ? String.fromCharCode(c) : "");
  return output;
}


function IMAP_UTF7( s ){
var c, d = "";
var tag = 0;

initBase64();

for (var i=0; i < s.length; i++){
 c = s.charCodeAt(i);
 if ( c = 0x26 )
 {
  d += "&-";
 /* tag = 0; */
 }
 else if ( 0x 20 <= c && c <= 0x7e )
 {
  if (tag == 1)
  {
   d += "&-";
  }
  d += s.charAt(i);
  tag = 0;
 }
 else if (0x7f <= c)
 {
  if (tag == 0)
  {
   d += "&";
  }
  d += base64Encode(s.charAt(i));
  tag = 1;
 }


}

alert(d);

}
</script>

<title>aa</title>

</head>

<body>
<a href="javascript:IMAP_UTF7('abcd대한민국')">Press</a>




6. ///////////////////////////////////////////////////////////////////////
6. ///////////////////////////////////////////////////////////////////////
ASP에서 BASE64 인코딩 & 디코딩.
Const sBASE_64_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

Function Base64decode(ByVal asContents)
Dim lsResult
Dim lnPosition
Dim lsGroup64, lsGroupBinary
Dim Char1, Char2, Char3, Char4
Dim Byte1, Byte2, Byte3
If Len(asContents) Mod 4 > 0 Then asContents = asContents & String(4 - (Len(asContents) Mod 4), " ")
lsResult = ""

For lnPosition = 1 To Len(asContents) Step 4
lsGroupBinary = ""
lsGroup64 = Mid(asContents, lnPosition, 4)
Char1 = INSTR(sBASE_64_CHARACTERS, Mid(lsGroup64, 1, 1)) - 1
Char2 = INSTR(sBASE_64_CHARACTERS, Mid(lsGroup64, 2, 1)) - 1
Char3 = INSTR(sBASE_64_CHARACTERS, Mid(lsGroup64, 3, 1)) - 1
Char4 = INSTR(sBASE_64_CHARACTERS, Mid(lsGroup64, 4, 1)) - 1
Byte1 = Chr(((Char2 And 48) \ 16) Or (Char1 * 4) And &HFF)
Byte2 = lsGroupBinary & Chr(((Char3 And 60) \ 4) Or (Char2 * 16) And &HFF)
Byte3 = Chr((((Char3 And 3) * 64) And &HFF) Or (Char4 And 63))
lsGroupBinary = Byte1 & Byte2 & Byte3
lsResult = lsResult + lsGroupBinary
Next
Base64decode = lsResult
End Function

Function Base64encode(ByVal asContents)
Dim lnPosition
Dim lsResult
Dim Char1
Dim Char2
Dim Char3
Dim Char4
Dim Byte1
Dim Byte2
Dim Byte3
Dim SaveBits1
Dim SaveBits2
Dim lsGroupBinary
Dim lsGroup64

If Len(asContents) Mod 3 > 0 Then asContents = asContents & String(3 - (Len(asContents) Mod 3), " ")
lsResult = ""

For lnPosition = 1 To Len(asContents) Step 3
lsGroup64 = ""
lsGroupBinary = Mid(asContents, lnPosition, 3)

Byte1 = Asc(Mid(lsGroupBinary, 1, 1)): SaveBits1 = Byte1 And 3
Byte2 = Asc(Mid(lsGroupBinary, 2, 1)): SaveBits2 = Byte2 And 15
Byte3 = Asc(Mid(lsGroupBinary, 3, 1))

Char1 = Mid(sBASE_64_CHARACTERS, ((Byte1 And 252) \ 4) + 1, 1)
Char2 = Mid(sBASE_64_CHARACTERS, (((Byte2 And 240) \ 16) Or (SaveBits1 * 16) And &HFF) + 1, 1)
Char3 = Mid(sBASE_64_CHARACTERS, (((Byte3 And 192) \ 64) Or (SaveBits2 * 4) And &HFF) + 1, 1)
Char4 = Mid(sBASE_64_CHARACTERS, (Byte3 And 63) + 1, 1)
lsGroup64 = Char1 & Char2 & Char3 & Char4
lsResult = lsResult + lsGroup64
Next

Base64encode = lsResult
End Function


[펌] http://www.jejusarang.com/?menu=knowhow&p=12&bwdt=1221669788