简体   繁体   中英

Elixir: Base64 decode TTN message

objective:

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.

The hex encoded message is: AWYQkQCsCPMANA==

what works:

My usual decoding goes like this:

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

And the function head of the actual decoder:

defp parse(<<a::1, b::1, _reserve::1, c::1, d::1, e::1, f::1, g::1, bat>>, <<data::binary>>) do

And that part works fine for a string like "01660dfa0109038d0030" . But somehow when TTN sends me the Base64 encoded raw payload, everything fails.

what doesn't work:

I'm trying to call the function Base.decode64!(raw_payload) |> decode() It gives me the error: ** (ArgumentError) non-alphabet digit found: "\x01" (byte 1)

Interestingly I have found out that if I Base.decode64!("AWYQkQCsCPMANA==") , I get <<1, 102, 16, 145, 0, 172, 8, 243, 0, 52>> , while https://cryptii.com/pipes/base64-to-hex returns me 01 66 10 91 00 ac 08 f3 00 34 . Why?

EDIT: To make it clear:

{flagsbat, string} = "AWYQkQCsCPMANA==" |> Base.decode64!() |> String.upcase() |> String.split_at(4)
Base.decode16!(flagsbat) # this throws the error


{flagsbat, string} = "0166109100ac08f30034" |> String.upcase() |> String.split_at(4)
Base.decode16!(flagsbat) # works

So how do I get the string which I can split and parse from the raw payload which is base64 encoded?

"0166109100ac08f30034" is what I get if I Base64 decode "AWYQkQCsCPMANA==" on https://cryptii.com/pipes/base64-to-hex

Turns out I need to Base16 encode the decoded Base64 to get an actual String.

Base.decode64!("AWYQkQCsCPMANA==") |> Base.encode16() |> decode()

That does trick and I can pass it normally into the decoding function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM