15. Validation de remplissage PKCS#7

15. Validation de remplissage PKCS#7

PKCS#7 padding validation

Write a function that takes a plaintext, determines if it has valid PKCS#7 padding, and strips the padding off.
The string:
"ICE ICE BABY\x04\x04\x04\x04"
... has valid padding, and produces the result "ICE ICE BABY".
The string:
"ICE ICE BABY\x05\x05\x05\x05"
... does not have valid padding, nor does:
"ICE ICE BABY\x01\x02\x03\x04"
If you are writing in a language with exceptions, like Python or Ruby, make your function throw an exception on bad padding.
Crypto nerds know where we're going with this. Bear with us.

Cet exercice est relativement simpliste, voici ma fonction de suppression de remplissage:

def padding_unset(bytes_string, block_length=16):
    try:
        if(len(bytes_string) != block_length):
            raise ValueError("Block does not match expected block length")
        last_byte_value = bytes_string[-1]
        
        if(last_byte_value >= block_length):
            return bytes_string
        elif(
            len(set(bytes_string[-last_byte_value:])) == 1 
            and all(bytes_string[i] >= block_length for i in range(0,block_length-last_byte_value))
        ):
            return bytes_string[:block_length-last_byte_value]
        else:
            raise ValueError("Invalid padding value")
    except Exception as e :
        logging.error(e)

Voilà ce que fait ce code :