title: Elixir: Base64 decode TTN message
body: <h1>objective:</h1>
  <p>I'm getting a base64 encoded raw payload from the things network. I'm trying to decode that on my server instead of using their javascript payload decoders.</p>
  <p>The hex encoded message is: <code>AWYQkQCsCPMANA==</code></p>
  <h1>what works:</h1>
  <p>My usual decoding goes like this:</p>
  <pre class="lang-elixir prettyprint-override"><code>def decode(string) do
    string = String.upcase(string)
    # get the first 2 bytes, which is 4 hex characters
    {flagsbat, string} = String.split_at(string, 4)
    parse(Base.decode16!(flagsbat), string)
  end
  </code></pre>
  <p>And the function head of the actual decoder:</p>
  <pre class="lang-elixir prettyprint-override"><code>defp parse(&lt;&lt;a::1, b::1, _reserve::1, c::1, d::1, e::1, f::1, g::1, bat&gt;&gt;, &lt;&lt;data::binary&gt;&gt;) do
  </code></pre>
  <p>And that part works fine for a string like <code>&quot;01660dfa0109038d0030&quot;</code>. But somehow when TTN sends me the Base64 encoded raw payload, everything fails.</p>
  <h1>what doesn't work:</h1>
  <p>I'm trying to call the function <code>Base.decode64!(raw_payload) |&gt; decode()</code>
  It gives me the error: <code>** (ArgumentError) non-alphabet digit found: &quot;\x01&quot; (byte 1)</code></p>
  <p>Interestingly I have found out that if I <code>Base.decode64!(&quot;AWYQkQCsCPMANA==&quot;)</code>, I get <code>&lt;&lt;1, 102, 16, 145, 0, 172, 8, 243, 0, 52&gt;&gt;</code>, while <a href="https://cryptii.com/pipes/base64-to-hex" rel="nofollow noreferrer">https://cryptii.com/pipes/base64-to-hex</a> returns me <code>01 66 10 91 00 ac 08 f3 00 34</code>. Why?</p>
  <p>EDIT:
  To make it clear:</p>
  <pre class="lang-elixir prettyprint-override"><code>{flagsbat, string} = &quot;AWYQkQCsCPMANA==&quot; |&gt; Base.decode64!() |&gt; String.upcase() |&gt; String.split_at(4)
  Base.decode16!(flagsbat) # this throws the error
  
  
  {flagsbat, string} = &quot;0166109100ac08f30034&quot; |&gt; String.upcase() |&gt; String.split_at(4)
  Base.decode16!(flagsbat) # works
  </code></pre>
  <p>So how do I get the string which I can split and parse from the raw payload which is base64 encoded?</p>
  <p>&quot;0166109100ac08f30034&quot; is what I get if I Base64 decode &quot;AWYQkQCsCPMANA==&quot; on <a href="https://cryptii.com/pipes/base64-to-hex" rel="nofollow noreferrer">https://cryptii.com/pipes/base64-to-hex</a></p>