1

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'
jsstuball
  • 4,104
  • 7
  • 33
  • 63

3 Answers3

4

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.

heemayl
  • 39,294
  • 7
  • 70
  • 76
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Why is there a newline character at the end of the base64_nonce? – jsstuball Feb 26 '18 at 08:18
  • 1
    That's added by `base64.encodebytes()`. You can use `.strip()` to remove it. Newlines have no meaning in the base64 encoding, so keeping it won't break anything. – Tomalak Feb 26 '18 at 08:52
1

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

client_nonce.to_bytes(2, byteorder='big')
kmaork
  • 5,722
  • 2
  • 23
  • 40
  • Calling `nonce = 0xf08c98caf1fd82e8cea9825dbff04fd0` and `nonce.to_bytes(2, byteorder='big')` gives me `OverflowError: int too big to convert`. – Tomalak Feb 26 '18 at 07:41
0

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=='
Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36