5

Is is possible to concatenate bytes to str?

>>> b = b'this is bytes'
>>> s = 'this is string'
>>> b + s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
>>> 

It is not possible based on simple code above.

The reason I'm asking this as I've seen a code where bytes has been concatenated to str? Here is the snipet of the code.

buf =  ""
buf += "\xdb\xd1\xd9\x74\x24\xf4\x5a\x2b\xc9\xbd\x0e\x55\xbd"

buffer = "TRUN /.:/" + "A" * 2003 + "\xcd\x73\xa3\x77" + "\x90" * 16 +  buf + "C" * (5060 - 2003 - 4 - 16 - len(buf))

You can see the full code here.

http://sh3llc0d3r.com/vulnserver-trun-command-buffer-overflow-exploit/

  • 1
    Please note that the second code only uses strings... – Tomerikoo Sep 30 '20 at 14:43
  • 1
    It's not possible as the error message implies. What you've shown isn't concatenating bytes to str, it is concatenating two str. Check `type("\xdb\xd1\xd9\x74\x24\xf4\x5a\x2b\xc9\xbd\x0e\x55\xbd")`. – juanpa.arrivillaga Sep 30 '20 at 14:43
  • Does this answer your question? [Can't concat bytes to str](https://stackoverflow.com/questions/21916888/cant-concat-bytes-to-str) ; https://stackoverflow.com/questions/46259640/cant-concat-bytes-to-str-converting-to-python3 – Tomerikoo Sep 30 '20 at 14:47
  • 1
    @juanpa.arrivillaga It's entirely possible that the code he's seen was written for Python 2.7, where `bytes` is just a synonym to `str`. That said, the code snippet he posted does not have bytes in it. – blhsing Sep 30 '20 at 14:47
  • Gosh .. b'' strings where str type in in python2. Op's link where the code he shows is from 2015 and most likely intended to run on python2 where that was perfectly fine.. – rasjani Sep 30 '20 at 14:47
  • I'm sorry, my bad. Should I delete this question? –  Sep 30 '20 at 14:47

2 Answers2

6

Either encode the string to bytes to get a result in bytes:

print(b'byte' + 'string'.encode())
# b'bytestring'

Or decode the bytes into a string to get a result as str:

print(b'byte'.decode() + 'string')
# bytestring
Wups
  • 2,489
  • 1
  • 6
  • 17
1

The second code snippet shows strings being concatenated. You will need to convert the bytes to a string (as shown in the question Convert bytes to a string). Try this: b.decode("utf-8") + s. It should give you the output you need.

Seth
  • 2,214
  • 1
  • 7
  • 21