Archived Forum Post

Index of archived forum posts

Question:

Base64 Encoding of a File to a String [UTF-8]

Jul 16 '14 at 14:26

Can you provide a code example of how to encode a PDF file to a Base64 string (not to another file)? This is not for emailing purposes. Assume UTF-8 character set.

Here is some more detail: I use vb6, so I start by getting the pdf file into a string, using the following function:

    Public Function FileGetBinaryString(ByRef as_File As String) As String
        Dim iFile As Integer
        iFile = FreeFile()
        Open as_File For Binary Access Read Lock Write As #iFile
        FileGetBinaryString = String$(LOF(iFile), Chr$(0))
        Get #iFile, , FileGetBinaryString
        Close #iFile
        Exit Function
    End Function

I then feed the resulting string to:

Chilkat_Crypt.Charset = "utf-8"

Chilkat_Crypt.CryptAlgorithm = "none"

Chilkat_Crypt.EncodingMode = "base64"

String_Encode_Base64 = Chilkat_Crypt.EncryptStringENC(the binary string)

But this doesn't seem to work properly (reverse decoding doesn't result in a proper pdf file).


Answer

VB6 strings are Unicode (not UTF-8) so you should use Chilkat_Crypt.Charset = "unicode" instead.

That said, you are better off working with byte arrays rather than strings for the file operations. Something like:

Option Explicit

Public Function FileGetBytes(ByVal p_FilePath As String) As Byte()
   Dim l_Ff As Integer

l_Ff = FreeFile()
   Open p_FilePath For Binary Access Read Lock Write As #l_Ff

ReDim FileGetBytes(LOF(l_Ff) - 1)

Get #l_Ff, , FileGetBytes
   Close #l_Ff
End Function

Public Function FileGetString(ByVal p_FilePath As String) As String
   Dim l_Ff As Integer

l_Ff = FreeFile()
   Open p_FilePath For Binary Access Read Lock Write As #l_Ff

FileGetString = String$(LOF(l_Ff), 0)

Get #l_Ff, , FileGetString
   Close #l_Ff
End Function

Sub TestBase64()
   Dim lo_CkCrypt As New Chilkat_v9_5_0.ChilkatCrypt2
   Dim l_Base64 As String
   Dim la_Bytes() As Byte

With lo_CkCrypt
      .UnlockComponent "Your Unlock Code"
      .Charset = "unicode"
      .CryptAlgorithm = "none"
      .EncodingMode = "base64"
   End With

' For Encoding
   l_Base64 = lo_CkCrypt.EncryptBytesENC(FileGetBytes("C:\test.pdf"))

' Example save string below
   Kill "C:\test.base64"
   Open "C:\test.base64" For Binary Access Write As #1
   Put #1, , l_Base64
   Close #1

' For Decoding
   la_Bytes = lo_CkCrypt.DecryptBytesENC(FileGetString("C:\test.base64"))

'Example save bytes below
   Kill "C:\test_decode.pdf"
   Open "C:\test_decode.pdf" For Binary Access Write As #1
   Put #1, , la_Bytes
   Close #1
End Sub

Answer

Many thanks, jpbro!

All I needed to change in my code was .Charset = "unicode" (instead of utf-8).

Much appreciated!