Alex's Notes

Byte and Hex String Manipulation

Python

Strings and Byte Strings


from sys import byteorder

# basic string type
a_string = "my string"
b_string = "another s"

num_bytes = len(a_string)

# returns byte string if valid ascii
a_bytes = a_string.encode('ascii')
b_bytes = b_string.encode('ascii')

# convert to int for xor
a_int = int.from_bytes(a_bytes, byteorder)
b_int = int.from_bytes(b_bytes, byteorder)

# now we can do bitwise xor
c_int = a_int ^ b_int

# can turn back to bytes
c_bytes = c_int.to_bytes(num_bytes, byteorder)
c_string = c_bytes.decode('ascii')

Hex Strings and Bytes


hex_string = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81"

hex_bytes = bytes.fromhex(hex_string)

# get the first 16 bytes
iv = hex_bytes[:16]
message = hex_bytes[16:]

# see the hex of the iv
iv_hex = iv.hex()
message_hex = message.hex()

# decode hex string to ascii
def decode_hex(hex_string):
    return bytes.fromhex(hex_string).decode('ascii')

Hex Strings and Integers (XOR)

hex_string = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81"

hex_to_int = int(hex_string, 16)

int_to_hex = hex(hex_to_int) # returns hex literal

hs1 = "4ca00ff4"
hs2 = "ab312aff"

# xor two hex strings and return result as hex string
def hex_xor(h1, h2):
    return str(hex( int(h1, 16) ^ int(h2, 16))[2:]

hex_xor(hs1, hs2)

Node

XOR two hex strings

function xor(hex1, hex2) {
  const buf1 = Buffer.from(hex1, 'hex');
  const buf2 = Buffer.from(hex2, 'hex');
  const bufResult = buf1.map((b, i) => b ^ buf2[i]);
  return bufResult.toString('hex');
}