gestumblinde

Gestumblinde - reference implementation of SLH-DSA
git clone git://www.tkruger.se/gestumblinde.git
Log | Files | Refs | README

utils.py (1014B)


      1 """
      2 Utilities from Section 4.4: "Arrays, Byte Strings, and Integers"
      3 and some additional ones.
      4 """
      5 
      6 import sys
      7 
      8 def cdiv(n, k):
      9     """Compute ceil(n/k)"""
     10     return (n + k - 1)//k
     11 
     12 def toInt(X: bytes, n: int) -> int:
     13     """Convert a byte string to an integer"""
     14     assert len(X) == n
     15     return int.from_bytes(X, byteorder="big")
     16 
     17 def toByte(x: int, n: int) -> bytes:
     18     """Convert an integer to a byte string"""
     19     assert n >= 0
     20     x %= (2**(8*n))
     21     return x.to_bytes(length=n, byteorder="big")
     22 
     23 def base_2b(X: bytes, b: int, out_len: int) -> list[int]:
     24     """Compute the base 2^b representation of X"""
     25     assert b > 0
     26     assert out_len >= 0
     27     n = len(X)
     28     assert n >= cdiv(out_len*b, 8)
     29     in_ = 0
     30     bits = 0
     31     total = 0
     32 
     33     baseb = []
     34     for _ in range(out_len):
     35         while bits < b:
     36             total = (total << 8) + X[in_]
     37             in_ += 1
     38             bits += 8
     39         bits -= b
     40         baseb.append((total >> bits) % (2**b))
     41     assert len(baseb) == out_len
     42     return baseb