Last active
October 3, 2023 06:55
-
-
Save nanmu42/b838acc10d393bc51cb861128ce7f89c to your computer and use it in GitHub Desktop.
Golang PKCS7 Padding/Unpadding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
Yes, I think that should be the case
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
Hi @aimuz , thanks for your feedback. What change should be made? Is it this?