Python Cryptography Tools: Difference between revisions

From Wiki
Jump to navigation Jump to search
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 9: Line 9:
>>> base64.b64encode(95616)
>>> base64.b64encode(95616)
TypeError: a bytes-like object is required, not 'int'
TypeError: a bytes-like object is required, not 'int'
</pre>
== Converting to Bytes ==
The most straightforward way to convert number-like objects into bytes-like objects seems to involve converting to string first.
<pre>
>>> bytes(bin(95616), 'ascii')
b'0b10111010110000000'
>>> bytes(hex(95616), 'ascii')
b'0x17580'
>>> base64.b64encode(bytes(str(95616), 'ascii'))
b'OTU2MTY='
</pre>
[https://en.wikipedia.org/wiki/Base64 Base64] uses 64 characters (and a padding symbol) to represent numbers in groups of six bits.  These don't line up nicely with sequences of bytes.
== XOR ==
<pre>
decoded_hex1 = bytes.fromhex("1c0111001f010100061a024b53535009181c")
decoded_hex2 = bytes.fromhex("686974207468652062756c6c277320657965")
xor_result = bytes(a ^ b for a, b in zip(decoded_hex1, decoded_hex2))
</pre>
== Hamming Distance ==
<pre>
def hammingDistance(bytes1, bytes2):
distance = 0
for a, b in zip(bytes1, bytes2):
xor_result = a ^ b
distance += bin(xor_result).count("1")
return distance
</pre>
</pre>

Latest revision as of 00:15, 9 February 2024

Encoding

Integers can be encoded as either binary, decimal, hexadecimal, or Base64 (among others).

>>> bin(95616)
'0b10111010110000000'
>>> hex(95616)
'0x17580'
>>> import base64
>>> base64.b64encode(95616)
TypeError: a bytes-like object is required, not 'int'

Converting to Bytes

The most straightforward way to convert number-like objects into bytes-like objects seems to involve converting to string first.

>>> bytes(bin(95616), 'ascii')
b'0b10111010110000000'
>>> bytes(hex(95616), 'ascii')
b'0x17580'
>>> base64.b64encode(bytes(str(95616), 'ascii'))
b'OTU2MTY='

Base64 uses 64 characters (and a padding symbol) to represent numbers in groups of six bits. These don't line up nicely with sequences of bytes.

XOR

decoded_hex1 = bytes.fromhex("1c0111001f010100061a024b53535009181c")
decoded_hex2 = bytes.fromhex("686974207468652062756c6c277320657965")
xor_result = bytes(a ^ b for a, b in zip(decoded_hex1, decoded_hex2))

Hamming Distance

def hammingDistance(bytes1, bytes2):
	distance = 0
	for a, b in zip(bytes1, bytes2):
		xor_result = a ^ b
		distance += bin(xor_result).count("1")
	return distance