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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM