github.com/wfusion/gofusion@v1.1.14/common/utils/cipher/padding.go (about)

     1  package cipher
     2  
     3  import (
     4  	"bytes"
     5  	"github.com/pkg/errors"
     6  )
     7  
     8  // PKCS7Pad Apply PKCS#7 padding
     9  func PKCS7Pad(data []byte, blockSize int) []byte {
    10  	if blockSize == 0 {
    11  		return data
    12  	}
    13  	padding := blockSize - len(data)%blockSize
    14  	return append(data, bytes.Repeat([]byte{byte(padding)}, padding)...)
    15  }
    16  
    17  // PKCS7Unpad Remove PKCS#7 padding
    18  func PKCS7Unpad(data []byte) ([]byte, error) {
    19  	length := len(data)
    20  	if length == 0 {
    21  		return data, nil
    22  	}
    23  	padding := int(data[length-1])
    24  	if padding == 0 || padding > len(data) {
    25  		return data, errors.New("invalid pkcs7 padding (padding size > data)")
    26  	}
    27  	for i := 1; i < padding; i++ {
    28  		if data[length-1-i] != byte(padding) {
    29  			return data, errors.New("invalid pkcs7 padding (pad[i] != padding text)")
    30  		}
    31  	}
    32  
    33  	return data[:(length - padding)], nil
    34  }