0

I'm trying to encode a string using like so:

base64.b64encode(b'username\with\backslash:password')

but printing only the string results in this

print('username\\with\\backslash:password')
>> username\withackslash:password

When escaping the backslashes with another backslash it prints this

print('username\\with\\backslash:password')
>> username\with\backslash:password

which looks good. But when base64 encoding and afterwards decoding it adds the extra slashes though

encoded=base64.b64encode(b'username\\with\\backslash:password')
print(encoded)
print(base64.b64decode(encoded))

>> b'dXNlcm5hbWVcd2l0aFxiYWNrc2xhc2g6cGFzc3dvcmQ='
>> b'username\\with\\backslash:password'

It encodes the escaping characters as well.

The same without escaping

encoded=base64.b64encode(b'username\with\backslash:password')
print(encoded)
print(base64.b64decode(encoded))

>> b'dXNlcm5hbWVcd2l0aAhhY2tzbGFzaDpwYXNzd29yZA=='
>> b'username\\with\x08ackslash:password'

Anyone got me a hint on how to encoding this right? I need this for http request authorization headers and my encoded strings won't be accepted so far.

axel wolf
  • 1,446
  • 3
  • 18
  • 29
  • 2
    You get the same thing out that you put in, the *literal* `b'username\\with\\backslash:password'`. There are only two backslashes total in there. The reason that it doesn't look like the *string* example you have at the beginning is that it's not a string, it's a `bytes`, which is always printed as a literal, not as the pure string contents. Try `print(base64.b64decode(encoded).decode())` to print a *string*. – deceze Mar 16 '23 at 08:04
  • @deceze namePw='username\\with\\backslash:password' encoded=base64.b64encode(str.encode(namePw)) print(encoded.decode()) print(base64.b64decode(encoded).decode()) A better way? Looks good in the results. Thanks. – axel wolf Mar 16 '23 at 08:22

0 Answers0