Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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&

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

今回のテストでは、これに合わせるために復号して得られたバイト配列に対して、 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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away


No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
Help us understand the problem. What is going on with this article?