Skip to content

Instantly share code, notes, and snippets.

@nanmu42
Last active October 3, 2023 06:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanmu42/b838acc10d393bc51cb861128ce7f89c to your computer and use it in GitHub Desktop.
Save nanmu42/b838acc10d393bc51cb861128ce7f89c to your computer and use it in GitHub Desktop.
Golang PKCS7 Padding/Unpadding
// pkcs7strip remove pkcs7 padding
func pkcs7strip(data []byte, blockSize int) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("pkcs7: Data is empty")
}
if length%blockSize != 0 {
return nil, errors.New("pkcs7: Data is not block-aligned")
}
padLen := int(data[length-1])
ref := bytes.Repeat([]byte{byte(padLen)}, padLen)
if padLen > blockSize || padLen == 0 || !bytes.HasSuffix(data, ref) {
return nil, errors.New("pkcs7: Invalid padding")
}
return data[:length-padLen], nil
}
// pkcs7pad add pkcs7 padding
func pkcs7pad(data []byte, blockSize int) ([]byte, error) {
if blockSize <= 1 || blockSize >= 256 {
return nil, fmt.Errorf("pkcs7: Invalid block size %d", blockSize)
} else {
padLen := blockSize - len(data) % blockSize
padding := bytes.Repeat([]byte{byte(padLen)}, padLen)
return append(data, padding...), nil
}
}
@aimuz
Copy link

aimuz commented Dec 19, 2022

Yes, I think that should be the case

@nanmu42
Copy link
Author

nanmu42 commented Dec 20, 2022

Yes, I think that should be the case

Thanks, I have updated the gist per your suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment