jsstuball
jsstuball

Reputation: 4911

Encode using base64, why am I getting wrong answer?

I am trying to authenticate for a websocket. In the example in the docs it says if my client nonce is:

nonce = 0xf08c98caf1fd82e8cea9825dbff04fd0 

then I should encode it using base64 to get:

target = "8IyYyvH9gujOqYJdv/BP0A==".

I'm not sure what I'm doing wrong but I get the following:

client_nonce = 0xf08c98caf1fd82e8cea9825dbff04fd0
str_client_nonce = str(client_nonce) 
encoded = b64encode(bytes(str_client_nonce, 'utf-8'))
print(encoded)

>> b'MzE5NzQ0NzM5NTUzODE1NjMyMTAxNjk0MjM1NzExODU0NjI4ODE2'

Upvotes: 1

Views: 2081

Answers (3)

Tomalak
Tomalak

Reputation: 338108

For starters, 0xf08c98caf1fd82e8cea9825dbff04fd0 is a number in Python (e.g. 0x10 is another way to write 16). But a number is not what you actually have, you have the hexadecimal representation of a list of bytes, also known as a hex string.

So things to do:

  • Get rid of the 0x, use a string.
  • Decode that string into bytes.
  • Encode those bytes to base64.

Code:

import base64

nonce_hex = 'f08c98caf1fd82e8cea9825dbff04fd0'
nonce = bytearray.fromhex(nonce_hex)
base64_nonce = base64.encodebytes(nonce)

# -> b'8IyYyvH9gujOqYJdv/BP0A==\n'

The actual nonce is always bytes. Different methods are being used to represent/store/transport those bytes. Using hex strings is one common way. Using base64 is another. Both hex strings and base64 serve the same purpose: To store arbitrary bytes in string form for easy handling. Base64 happens to need less space than hex strings, this is why it is often preferred. The above code just converts one string representation of bytes into another.

Upvotes: 4

kmaork
kmaork

Reputation: 6012

str(client_nonce) gives you '0xf08...' while you probably what to convert it directly to bytes:

client_nonce.to_bytes(2, byteorder='big')

Upvotes: 1

Maarten Fabré
Maarten Fabré

Reputation: 7058

you have to convert your nonce to a bytes directly. Not the string representation

via https://stackoverflow.com/a/45586011/1562285

b = int2bytes(nonce)
b'\xf0\x8c\x98\xca\xf1\xfd\x82\xe8\xce\xa9\x82]\xbf\xf0O\xd0'
base64.b64encode(b)
b'8IyYyvH9gujOqYJdv/BP0A=='

Upvotes: 0

Related Questions