Trying to send string variable via Python socket

Question:

I’m in a CTF competition and I’m stuck on a challenge where I have to retrieve a string from a socket, reverse it and get it back. The string changes too fast to do it manually. I’m able to get the string and reverse it but am failing at sending it back. I’m pretty sure I’m either trying to do something that’s not possible or am just too inexperienced at Python/sockets/etc. to kung fu my way through.

Here’s my code:

import socket

aliensocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

aliensocket.connect(('localhost', 10000))
  
aliensocket.send('GET_KEY'.encode())
key = aliensocket.recv(1024)

truncKey = str(key)[2:16]
revKey = truncKey[::-1]

print(truncKey)
print(revKey)

aliensocket.send(bytes(revKey.encode('UTF-8')))
print(aliensocket.recv(1024))

aliensocket.close()

And here is the output:

F9SIJINIK4DF7M
M7FD4KINIJIS9F
b'Server expects key to unlock or GET_KEY to retrieve the reversed key'
Asked By: Jodi Rehlander

||

Answers:

data  = ''
while True:
   chunk = aliensocket.recv(1)
   data +=chunk
   if not chunk:
        rev = data[::-1]
        aliensocket.sendall(rev)
        break
Answered By: cacoch

key is received as a byte string. The b'' wrapped around it when printed just indicates it is a byte string. It is not part of the string. .encode() turns a Unicode string into a byte string, but you can just mark a string as a byte string by prefixing with b.

Just do:

aliensocket.send(b'GET_KEY')
key = aliensocket.recv(1024)
revKey = truncKey[::-1]
print(truncKey)  # or do truncKey.decode() if you don't want to see b''
print(revKey)
aliensocket.send(revKey)
Answered By: Mark Tolonen
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.