Converting a base64 string to a Hex string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jeremy Kitchen

    Converting a base64 string to a Hex string

    Are there any library functions that can help me to do this? If
    necessary I can convert the string to a byte array. I don't want to
    have to write my own Hex conversion if it isn't necessary.

    Thanks for any help
    Jeremy Kitchen

  • jayeldee

    #2
    Re: Converting a base64 string to a Hex string

    On Mar 13, 9:54 am, "Jeremy Kitchen" <J.t.Kitc...@gm ail.comwrote:
    Are there any library functions that can help me to do this? If
    necessary I can convert the string to a byte array. I don't want to
    have to write my own Hex conversion if it isn't necessary.
    >
    Thanks for any help
    Jeremy Kitchen
    Forgive me if I'm way off, but do you want to take a string such as
    "1234ABCDEF G" and end up with "31323334414243 44"?

    You can use the ASCII object in System.Text.Asc iiEncoding to get the
    bytes of the string, then convert each byte to a Hex string with the
    ToString overload that accepts a format.

    Dim sBase As String = "1234ABCD"
    Dim bBase() As Byte
    Dim sHex As String = String.Empty
    Dim sHexByte As String

    bBase = System.Text.ASC IIEncoding.ASCI I.GetBytes(sBas e)

    For i As Integer = 0 To bBase.Length - 1
    sHexByte = bBase(i).ToStri ng("x")
    If sHexByte.Length = 0 Then
    sHexByte = "0" & sHexByte
    End If
    sHex &= sHexByte
    Next

    Console.WriteLi ne(sHex)
    Console.ReadLin e()

    Comment

    • Branco Medeiros

      #3
      Re: Converting a base64 string to a Hex string

      jayeldee wrote:
      >
      Dim sBase As String = "1234ABCD"
      Dim bBase() As Byte
      Dim sHex As String = String.Empty
      Dim sHexByte As String
      >
      bBase = System.Text.ASC IIEncoding.ASCI I.GetBytes(sBas e)
      >
      For i As Integer = 0 To bBase.Length - 1
      sHexByte = bBase(i).ToStri ng("x")
      If sHexByte.Length = 0 Then
      sHexByte = "0" & sHexByte
      End If
      sHex &= sHexByte
      Next
      >
      Console.WriteLi ne(sHex)
      Console.ReadLin e()
      Just a few suggestions, hope you don't mind...

      You don't need to keep track of the byte index (the For i As
      Integer... loop). Instead you may want to use a For Each loop -- just
      a question of preference, though, but the loop may become more
      "readable":

      For Each B As Byte In Sytem.Text.Enco ding. _
      ASCII.GetBytes( Base64Text)
      ...
      Next

      Also, you'll be glad to know that the ToString("x") method of the
      integer data types (Byte, Integer, Long, UInteger, etc) allows a
      "length" parameter, so you don't have to manually padd the returned
      string:

      For Each B As Byte In Sytem.Text.Enco ding. _
      ASCII.GetBytes( Base64Text)
      'HexChar will be zero-padded up to two digits
      Dim HexChar As String = B.ToString("x2" )
      ...
      Next

      Finally, just remember that base64 encoded strings are *usually* used
      to encode a large amount of data. Concatenating strings in a loop
      using the "&" operator is not a real problem if the number of
      iterations is small -- but, how many is "small"? Don't ask me.
      Personally, I'll resort to a StringBuilder whenever I see a loop. Of
      course, there's no rule in stone, here. But since we may consider that
      the typical content of a base64 encoded string can be quite large, the
      use of a StringBuilder may be advised:

      Dim S As New System.Text.Str ingBuilder
      For Each B As Byte In Sytem.Text.Enco ding. _
      ASCII.GetBytes( Base64Text)
      S.Append(B.ToSt ring("x2"))
      Next
      HexText = S.ToString


      Just for the fun of it (and if the OP doesn't mind writing VB code
      that threads on the limits of readability), we could also have:

      Public Function CharToHex(Value As Char) As String
      Return Convert.ToByte( Value).ToString ("x2")
      End Function

      '...
      HexText = String.Join(Not hing, _
      System.Array.Co nvertAll(Of Char, String)( _
      Base64Text.ToCh arArray, AddressOf CharToHex))


      :-))

      Regards,

      Branco.

      Comment

      • jayeldee

        #4
        Re: Converting a base64 string to a Hex string

        On Mar 13, 3:42 pm, "Branco Medeiros" <branco.medei.. .@gmail.com>
        wrote:
        jayeldee wrote:
        Just a few suggestions, hope you don't mind...
        Awesome suggestions. I just made it quick, dirty, and readable. I
        forgot about the padding of the string and probably should've used a
        StringBuilder (I almost always do in any examples I toss together.)


        Comment

        • Oenone

          #5
          Re: Converting a base64 string to a Hex string

          Jeremy Kitchen wrote:
          Are there any library functions that can help me to do this? If
          necessary I can convert the string to a byte array. I don't want to
          have to write my own Hex conversion if it isn't necessary.
          Is this what you want?

          \\\
          Dim ret As String
          'b64 is a string containing base-64 encoded data
          Dim b64 As String = "VXNlcm5hbW U6"
          'Decode the base64 data to a byte array
          Dim b64bytes() As Byte = System.Convert. FromBase64Strin g(b64)

          'Loop through each byte, adding the hex value for each byte to our
          return string
          For Each b As Byte In b64bytes
          ret &= Hex(b).PadLeft( 2, "0"c)
          Next

          'Display the finished string
          MsgBox(ret)
          ///

          --

          (O)enone



          Comment

          • Jeremy Kitchen

            #6
            Re: Converting a base64 string to a Hex string

            On Mar 14, 5:39 am, "Oenone" <oen...@nowhere .comwrote:
            Jeremy Kitchen wrote:
            Are there any library functions that can help me to do this? If
            necessary I can convert the string to a byte array. I don't want to
            have to write my own Hex conversion if it isn't necessary.
            >
            Is this what you want?
            >
            \\\
            Dim ret As String
            'b64 is a string containing base-64 encoded data
            Dim b64 As String = "VXNlcm5hbW U6"
            'Decode the base64 data to a byte array
            Dim b64bytes() As Byte = System.Convert. FromBase64Strin g(b64)
            >
            'Loop through each byte, adding the hex value for each byte to our
            return string
            For Each b As Byte In b64bytes
            ret &= Hex(b).PadLeft( 2, "0"c)
            Next
            >
            'Display the finished string
            MsgBox(ret)
            ///
            >
            --
            >
            (O)enone

            Thanks everyone.

            Comment

            • Jeremy Kitchen

              #7
              Re: Converting a base64 string to a Hex string

              On Mar 14, 8:38 am, "Jeremy Kitchen" <J.t.Kitc...@gm ail.comwrote:
              On Mar 14, 5:39 am, "Oenone" <oen...@nowhere .comwrote:
              >
              >
              >
              Jeremy Kitchen wrote:
              Are there any library functions that can help me to do this? If
              necessary I can convert the string to a byte array. I don't want to
              have to write my own Hex conversion if it isn't necessary.
              >
              Is this what you want?
              >
              \\\
              Dim ret As String
              'b64 is a string containing base-64 encoded data
              Dim b64 As String = "VXNlcm5hbW U6"
              'Decode the base64 data to a byte array
              Dim b64bytes() As Byte = System.Convert. FromBase64Strin g(b64)
              >
              'Loop through each byte, adding the hex value for each byte to our
              return string
              For Each b As Byte In b64bytes
              ret &= Hex(b).PadLeft( 2, "0"c)
              Next
              >
              'Display the finished string
              MsgBox(ret)
              ///
              >
              --
              >
              (O)enone
              >
              Thanks everyone.

              Ack, I am having trouble getting it to convert back to base64

              Imports System.Text
              Module Module1

              Sub Main()
              Dim baseStr As String = "4WUC/38ff+GAm2GGOeR5 Up7fi5Q0RU
              +h8Zf5vKsOtXE="
              Console.WriteLi ne(baseStr)
              Console.WriteLi ne(Base64ToHex( baseStr))
              Console.WriteLi ne()

              Console.WriteLi ne(baseStr)
              Console.WriteLi ne(HexToBase64( Base64ToHex(bas eStr)))
              Console.ReadLin e()
              End Sub

              Function Base64ToHex(ByV al sBase As String) As String
              Dim bBase() As Byte = Convert.FromBas e64String(sBase )
              Dim Hex As New StringBuilder

              For Each HexByte As Byte In bBase
              Console.Write(H exByte & " ")
              Hex.Append(HexB yte.ToString("x 2"))
              Next
              Console.WriteLi ne()
              Return Hex.ToString.To Upper
              End Function
              Private Function HexToBase64(ByV al HexText As String) As String
              Dim result(HexText. Length) As Byte

              Dim i As Integer = 0
              While i < HexText.Length
              result(i) = Convert.ToByte( HexText.Substri ng(i, 2), 16)
              Console.Write(r esult(i) & " ")
              i += 2
              End While
              Console.WriteLi ne()

              Return Convert.ToBase6 4String(result)
              End Function
              End Module

              It is returning a much different string than I started with

              Comment

              • \(O\)enone

                #8
                Re: Converting a base64 string to a Hex string

                Jeremy Kitchen wrote:
                Ack, I am having trouble getting it to convert back to base64
                It's because you're not accounting for each byte taking two characters
                within the string.

                Try replacing your HexToBase64 function with the following:

                \\\
                Private Function HexToBase64(ByV al HexText As String) As String
                Dim result(HexText. Length \ 2) As Byte

                Dim i As Integer = 0
                While i < HexText.Length \ 2
                result(i) = Convert.ToByte( HexText.Substri ng(i * 2, 2), 16)
                Console.Write(r esult(i) & " ")
                i += 1
                End While
                Console.WriteLi ne()

                Return Convert.ToBase6 4String(result)
                End Function
                ///

                HTH,
                --

                (O)enone


                Comment

                • Jeremy Kitchen

                  #9
                  Re: Converting a base64 string to a Hex string

                  On Mar 14, 2:01 pm, "\(O\)enone " <oen...@nowhere .comwrote:
                  Jeremy Kitchen wrote:
                  Ack, I am having trouble getting it to convert back to base64
                  >
                  It's because you're not accounting for each byte taking two characters
                  within the string.
                  >
                  Try replacing your HexToBase64 function with the following:
                  >
                  \\\
                  Private Function HexToBase64(ByV al HexText As String) As String
                  Dim result(HexText. Length \ 2) As Byte
                  >
                  Dim i As Integer = 0
                  While i < HexText.Length \ 2
                  result(i) = Convert.ToByte( HexText.Substri ng(i * 2, 2), 16)
                  Console.Write(r esult(i) & " ")
                  i += 1
                  End While
                  Console.WriteLi ne()
                  >
                  Return Convert.ToBase6 4String(result)
                  End Function
                  ///
                  >
                  HTH,
                  --
                  >
                  (O)enone
                  I eventually realized said fact...and fixed it. Thanks for the help
                  though

                  Comment

                  • Branco Medeiros

                    #10
                    Re: Converting a base64 string to a Hex string

                    Jeremy Kitchen wrote:
                    <snip>
                    Ack, I am having trouble getting it to convert back to base64
                    <snip>
                    Private Function HexToBase64(ByV al HexText As String) As String
                    Dim result(HexText. Length) As Byte
                    >
                    Dim i As Integer = 0
                    While i < HexText.Length
                    result(i) = Convert.ToByte( HexText.Substri ng(i, 2), 16)
                    Console.Write(r esult(i) & " ")
                    i += 2
                    End While
                    Console.WriteLi ne()
                    >
                    Return Convert.ToBase6 4String(result)
                    End Function
                    <snip>

                    The size of Result must be half of the hex-string size; also, its
                    index is independent of the index that traverses the hex-string.

                    <code>
                    Private Function HexToBase64(ByV al HexText As String) As String
                    Dim Size As Integer = HexText.Length
                    Dim Result(0 To (Size >1) - 1) As Byte
                    Dim Pos As Integer
                    For Index As Integer = 0 To Size - 1 Step 2
                    Result(Pos) = Convert.ToByte( HexText.Substri ng(Index, 2), 16)
                    Pos += 1
                    Next
                    Return Convert.ToBase6 4String(Result)
                    End Function
                    </code>

                    HTH.

                    Regards,

                    Branco.

                    Comment

                    Working...