如何在不先将其元素转换为 int 的情况下旋转 python 中的 bytearray 键?

How to rotate a bytearray key in python without converting it's elements to an int first?

我正在尝试实现可用作 DES 轮密钥的密钥计划功能。所以我写的关键调度函数应该将输入作为 8 字节的字节数组并旋转它(而不是移位)特定的位数。但是看不到如何实现它,因为将字节数组转换为 int 迟早会导致错误。我试过的是:

def key_sckedule(key: bytearray):
    """
    A function that takes a key as bytes input and use a permutation to mutate the key and return a
    mutated key that can act as be used as a sub key for a DES-round. The permutation is right rotation by
    1-Bit for round 1, 2, 9, 16 and 2-Bits for all other rounds.

    :param key: a bytes object representing the key use minimum key size of 8-bytes (64-Bit).
    :return: The round key
    """
    if len(key) < 8:
        raise ValueError("Size is less than 8-Bytes")

    global __round_number
    if __round_number in [1, 2, 9, 16]:
        shift_value = 1
    else:
        shift_value = 2

    key_to_int = int(key)
    key_to_int = key_to_int >> shift_value
    __round_number += 1

    print(key_to_int)
    return bytearray(key_to_int.to_bytes(8, byteorder="little"))

要将字节数组转换为整数,请使用:

int(b.hex(), 16)

要朝另一个方向走,请使用:

value.to_bytes(length, 'big')

其中 length 是原始字节数组的长度。

注意旋转k位时,需要将低位k位左移total_length_in_bits - k,或将原值右移k