[Python] Performing bitwise operations on very large integers in python

Discussão em 'Python' iniciado por Stack, Junho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm making an implementation of the SHA-1 algorithm in python for a school project. My code breaks because it generates an integer too large for my school's IDE to handle.

    Because bit manipulation isn't python's strong suit, I've had to resort to building my code off of a lot of clunky utility functions and binary strings. Worked fine for the first half of the project, but my code's actual hashing process uses integers and that's what crashes it.

    ***I only have access to built-in modules, so this has proven to be a pretty difficult task. I would've handled something like this in numpy, but I am unable to.

    def generate_temp(
    a:int,
    f:int,
    e:int,
    k:int,
    current_word: str
    ) -> int:

    temp = leftrotate_util(str(a), 5) + str(f) + str(e) + str(k) + current_word
    return int(temp)

    def hashing():
    words = digest()
    h0,h1,h2,h3,h4 = (0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0)
    a,b,c,d,e = h0,h1,h2,h3,h4

    for i in range(0, 80):
    if i <= 19:
    and_res = operator.and_(b,c)
    not_res = operator.not_(b)
    and_res1 = operator.and_(not_res, d)
    or_res = operator.or_(and_res, and_res1)

    f: int = or_res
    k: Final[int] = 0x5A827999

    elif i <= 39:
    f = b ^ c ^ d
    k: Final[int] = 0x6ED9EBA1

    elif i <= 59:
    and_res = operator.and_(b,c)
    and_res1 = operator.and_(b,d)
    and_res2 = operator.and_(c,d)
    xor_res = and_res ^ and_res1 ^ and_res2

    f = xor_res
    k: Final[int] = 0x8F1BBCDC

    elif i <= 79:
    f = b ^ c ^ d
    k: Final[int] = 0xCA62C1D1

    temp = generate_temp(a, f, e, k, words)
    e = d
    d = c
    c = int(leftrotate_util(str(b), 30))
    b = a
    a = temp

    h0 = str(h0) + str(a)
    h1 = str(h1) + str(b)
    h2 = str(h1) + str(c)
    h3 = str(h2) + str(d)
    h4 = str(h4) + str(e)


    I'm not sure what the best way to tackle this is. I've considered representing the integers as arrays, but I'm not sure how to perform bitwise operations on them.

    Continue reading...

Compartilhe esta Página