2

I'm trying to assemble a byte array in Python for a signature that resembles the following:

  • 4 bytes that represent the length, in bytes, of String A.
  • String A
  • 4 bytes that represent the length, in bytes, of String B.
  • String B
  • 4 bytes that represent the length, in bytes, of the Long A value.
  • Long A

String A + B are utf-8 which I converted to utf-8 using unicode(string, 'utf-8')

I've tried converting each item to a byte array and joining them using the plus symbol e.g.

bytearray(len(a)) + bytearray(a, "utf-8")...

I've also stried using struct.pack e.g.

struct.pack("i", len(a)) + bytearray(access_token, "utf-8")...

But nothing seems to generate a valid signature. Is this the right way to make the above byte array in Python?

6
  • 2
    How do you know the signature is not valid? Commented Sep 23, 2015 at 13:02
  • 1
    please post some example data. Commented Sep 23, 2015 at 13:06
  • FWIW, unicode(some_string, 'utf-8') converts the byte string some_string to a Unicode string. The 'utf-8' arg says that the source string is encoded in utf-8. Commented Sep 23, 2015 at 13:10
  • You should also mention whether those length values need to be formatted as big-endian or little-endian. I assume this is for some Net thing, so you probably want big-endian, but it's nice to be explicit. :) Commented Sep 23, 2015 at 13:15
  • possible duplicate of How to convert integer value to array of four bytes in python Commented Sep 23, 2015 at 13:15

1 Answer 1

2

The last question is about endianness of the 4 byte lengths, but you can easily control it with the struct module.

I would use

def dopack(A, B, LongA):
    fmt='!'  # for network order, use < for little endian, > for big endian, = for native
    fmt += 'i'

    buf = pack(fmt, len(A))
    buf += A
    buf += pack(fmt, len(B))
    buf += B
    b = bytes(LongA)
    buf += pack(fmt, len(b))
    buf += B

In this way, the LongA value is coded in ASCII, but it is easier, and you can just do int(b) do convert it back to a long.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.