Sunday, June 17, 2012

MSXML Encode Decode Base64

Private Function EncodeBase64(ByRef arrData() As Byte) As String

Dim objXML As MSXML2.DOMDocument
Dim objNode As MSXML2.IXMLDOMElement

' help from MSXML
Set objXML = New MSXML2.DOMDocument

' byte array to base64
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.Text

' thanks, bye
Set objNode = Nothing
Set objXML = Nothing

End Function

Private Function DecodeBase64(ByVal strData As String) As Byte()

Dim objXML As MSXML2.DOMDocument
Dim objNode As MSXML2.IXMLDOMElement

' help from MSXML
Set objXML = New MSXML2.DOMDocument
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.Text = strData
DecodeBase64 = objNode.nodeTypedValue

' thanks, bye
Set objNode = Nothing
Set objXML = Nothing

End Function

Public Sub Main()

Dim strData As String

strData = EncodeBase64(StrConv("Greetings and Salutations", vbFromUnicode))
Debug.Print strData
Debug.Print StrConv(DecodeBase64(strData), vbUnicode)

End Sub