Skip to content

Instantly share code, notes, and snippets.

@carlfriess
Last active October 14, 2021 13:52
Show Gist options
  • Save carlfriess/15d47e58cbc3346d1430b189c3a6f672 to your computer and use it in GitHub Desktop.
Save carlfriess/15d47e58cbc3346d1430b189c3a6f672 to your computer and use it in GitHub Desktop.
Tips and tricks to help you with module 02 of Information Security Lab
# Encoding and parsing integers
# https://docs.python.org/3/library/stdtypes.html#int.to_bytes
# https://docs.python.org/3/library/stdtypes.html#int.from_bytes
bytes = (42).to_bytes(2, 'big') # 16-bit integer, big-endian
num = int.from_bytes(bytes, 'big') # Notice: length is implicit
# Encoding and parsing strings
# https://www.programiz.com/python-programming/methods/string/encode
bytes = "Hello, World!".encode()
string = b"Hello, World!".decode()
# Reading RFC8446:
# Make sure to read section 3: Presentation Language
# https://www.rfc-editor.org/rfc/rfc8446.html#section-3
# Example message:
# struct {
# Version version = 0x00000001;
# char name<0..512>;
# opaque data[16];
# } Example;
# Encoding the message:
def encode(name, data):
# struct {
# Version version = 0x00000001;
msg = 0x00000001.to_bytes(4, 'big')
# char name<0..512>;
msg += len(name).to_bytes(2, 'big')
msg += name.encode()
# opaque data[16];
if len(data) != 16:
raise TypeError("data too short")
msg += data
# } Example;
return msg
# Decode the message:
def decode(msg):
pos = 0
# struct {
# Version version = 0x00000001;
version = int.from_bytes(msg[pos:pos+4], 'big')
pos += 4
# char name<0..512>;
name_len = int.from_bytes(msg[pos:pos+2], 'big')
pos += 2
name = msg[pos:pos+name_len].decode()
pos += name_len
# opaque data[16];
data = msg[pos:pos+16]
# } Example;
return version, name, data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment