python实现PKCS5Padding

python实现PKCS5Padding

    python实现PKCS5Padding
    2008-09-21

    请参考
    ssl-3-padding-mode
    php的加密函数库
    DES加密的Python和PHP实现

    在PKCS5Padding中,明确定义Block的大小是8位
    而在PKCS7Padding定义中,对于块的大小是不确定的,可以在1-255之间

    PKCS #7 填充字符串由一个字节序列组成,每个字节填充该字节序列的长度。
    假定块长度为 8,数据长度为 9,
    数据: FF FF FF FF FF FF FF FF FF
    PKCS7 填充: FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07

    def nrPadBytes(blocksize, size):
      'Return number of required pad bytes for block of size.'
      if not (0 < blocksize < 255):
        raise Error('blocksize must be between 0 and 255')
      return blocksize - (size % blocksize)

    def appendPadding(blocksize, s):
      '''Append rfc 1423 padding to string.

      RFC 1423 algorithm adds 1 up to blocksize padding bytes to string s. Each
      padding byte contains the number of padding bytes.
      '''
      n = nrPadBytes(blocksize, len(s))
      return s + (chr(n) * n)

    def removePadding(blocksize, s):
      'Remove rfc 1423 padding from string.'
      n = ord(s[-1]) # last byte contains number of padding bytes
      if n > blocksize or n > len(s):
        raise Error('invalid padding')
      return s[:-n]

    PKCS5的另一种

                pad_len = 8 - (len(data) % self.block_size)
                if _pythonMajorVersion < 3:
                    data += pad_len * chr(pad_len)
                else:
                    data += bytes([pad_len] * pad_len)



                if _pythonMajorVersion < 3:
                    pad_len = ord(data[-1])
                else:
                    pad_len = data[-1]
                data = data[:-pad_len]

    第3种

    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    unpad = lambda s : s[0:-ord(s[-1])]

    tags: PKCS5
    发表在 Python, 软件逆向工程 作者 zhiwei

原文地址:https://www.cnblogs.com/lexus/p/3382580.html