Danger

Nothing here should be used for any security purposes.

  • If you need cryptographic tools in a Python environment use pyca.

  • If you need efficient and reliable abstract math utilities in a Python-like environment consider using SageMath.

Bit manipulation utiltieis

This module is imported with:

import toy_crypto.bit-like_utils

Examples

Just a few examples.

bits() is used by scaler_multiply() and would be used by leaky modular exponentiation if I had included that.

>>> from toy_crypto.bit_utils import bits
>>> list(bits(13))
[1, 0, 1, 1]

Let’s illustrate hamming_distance() with an example from Cryptopals.

>>> from toy_crypto.bit_utils import hamming_distance
>>> s1 = b"this is a test"
>>> s2 = b"wokka wokka!!!"
>>> hamming_distance(s1, s2)
37

The publically available parts

Note again that this module is most subject to change.

Various utilities for manipulationg bit-like things.

The utilities here are most subject to change as many where just quick things I needed. This is more of a trash heap than a well-thought-out module.

class toy_crypto.bit_utils.Bit(b: SupportsBool) None[source]

Because I made poor choices earlier of how to represent bits, I need an abstraction.

Parameters:

b (SupportsBool)

as_bytes() bytes[source]

Returns a big-endian byte. Either 0x00 or 0x01.

Return type:

bytes

as_int() int[source]

Returns 0 or 1.

Return type:

int

toy_crypto.bit_utils.bit_index(n: int, k: int, b: bool | int = 1) int | None[source]

Returns which bit is the k-th b bit in n.

This is to mimic bitarray.utils.count_n, but for working with python built-in int

Parameters:
Return type:

int | None

toy_crypto.bit_utils.bit_index_linear(n: int, k: int, b: bool | int = 1) int | None[source]

Returns which bit is the k-th b bit in n.

This is to mimic bitarray.utils.count_n, but for working with python built-in int

Parameters:
Return type:

int | None

toy_crypto.bit_utils.bits(n: int) Iterator[int][source]

0s and 1s representing bits of n, starting with the least significant bit.

Raises:

ValueError – if n is negative.

Parameters:

n (int)

Return type:

Iterator[int]

toy_crypto.bit_utils.flip_end(byte: int) int[source]

Return int with reversed bit sequence

Parameters:

byte (int)

Return type:

int

toy_crypto.bit_utils.get_bit(n: int, k: int) int[source]

returns k-th bit of n.

Parameters:
Return type:

int

toy_crypto.bit_utils.hamming_distance(a: bytes, b: bytes) int[source]

Hamming distance between byte sequences of equal length.

Raises:

ValueError – if len(a) != len(b).

Parameters:
Return type:

int

toy_crypto.bit_utils.set_bit(n: int, k: int, value: bool | int = True) int[source]

Returns copy of n with k-th bit set to value.

Parameters:
Return type:

int

toy_crypto.bit_utils.set_bit_in_byte(byte: int, bit: int, value: SupportsBool) int[source]

Sets the bit-most significant bit to value in byte.

Parameters:
Return type:

int