LoginSignup
1
5

More than 5 years have passed since last update.

VBAでWindowsAPIを使って、Base64文字列を バイト配列に復号

Posted at

Base64の変換アルゴリズムは割とシンプルでオウンコーディングできる程度のものですが、実はWindows APIが その機能を提供しています。
VBAで、これを使って、Base64文字列を バイト配列に復号する方法を記します。

主となる関数
Private Declare PtrSafe Function CryptStringToBinary Lib "Crypt32.dll" Alias "CryptStringToBinaryW" ( _
    ByVal pszString As LongPtr, _
    ByVal cchString As Long, _
    ByVal dwFlags As Long, _
    ByVal pbBinary As LongPtr, _
    ByVal pcbBinary As LongPtr, _
    ByVal pdwSkip As LongPtr, _
    ByVal pdwFlags As LongPtr _
    ) As Long

Private Const CRYPT_STRING_BASE64 As Long = &H1&

'バイト配列をBASE64でエンコードしたUnicode文字列にする関数
Public Function CryptStringToByte(ByRef sData As String) As Byte()
    CryptStringToByte = ""
    If Len(sData) = 0 Then
        Exit Function
    End If

    Dim pszString As LongPtr
    Dim cchString As Long
    pszString = StrPtr(sData)
    cchString = Len(sData)

    Dim nBufferSize As Long
    Dim bBuffer() As Byte

    '変換後文字列の長さを取得し、変換後文字列を格納するだけのバッファを用意
    If CryptStringToBinary(pszString, cchString, CRYPT_STRING_BASE64, 0, VarPtr(nBufferSize), 0, 0) Then
        If nBufferSize Then
            ReDim bBuffer(0 To nBufferSize - 1)
            If CryptStringToBinary(pszString, cchString, CRYPT_STRING_BASE64, VarPtr(bBuffer(0)), VarPtr(nBufferSize), 0, 0) Then
                 CryptStringToByte = bBuffer
            End If
        End If
    End If

End Function

以下がテストコードです。
wikipediaのBase64の項目に載っている"ABCDEFG"のBase64変換結果を逆変換してみます。
wikipediaの変換結果は、ASCII文字列あるいはSJISとしてみた場合の"ABCDEFG"の変換結果です。
今回のテストでは、これに合わせるために復号して得られたバイト配列に対して、 SJIS->Unicodeの変換を行っています。

テストコード
'上のコードの下に続けて、以下のコードを書いてください。
'Base64の文字列を Byte配列に復号し、そのByte配列を SJIS文字列とみなして、Unicode文字列に変換する関数
Public Function Base64_String_To_SJISString(ByVal sValue As String) As String
    Dim bBytes() As Byte
    bBytes = CryptStringToByte(sValue)
    If UBound(bBytes) = -1 Then
        Exit Function
    End If

    Base64_String_To_SJISString = StrConv(bBytes, vbUnicode)

End Function

Sub Main()
    Debug.Print Base64_String_To_SJISString("gqA=")
    Debug.Print Base64_String_To_SJISString("QUJDREVGRw==")

End Sub
あ
ABCDEFG
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5