Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unpad add the format valid #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions pkcs7.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,26 @@ func Pad(buf []byte, size int) ([]byte, error) {
}

func Unpad(padded []byte, size int) ([]byte, error) {
if len(padded)%size != 0 {
paddedLen := len(padded)

if paddedLen%size != 0 {
return nil, errors.New("pkcs7: Padded value wasn't in correct size.")
}

bufLen := len(padded) - int(padded[len(padded)-1])
lastPad := padded[paddedLen-1]
padLen := int(lastPad)

if padLen > size {
return nil, errors.New("pkcs7: Padded value larger than size.")
}

for i := paddedLen - padLen; i < paddedLen; i++ {
if padded[i] != lastPad {
return nil, errors.New("pkcs7: Padded value wasn't in correct format.")
}
}

bufLen := paddedLen - padLen
buf := make([]byte, bufLen)
copy(buf, padded[:bufLen])
return buf, nil
Expand Down
16 changes: 16 additions & 0 deletions pkcs7_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,22 @@ func TestPkcs7(t *testing.T) {
}
})

t.Run("Unpads error length", func(t *testing.T) {
_, err := Unpad([]byte("123456789012345678901234567890123456789012345678901234567890\x11\x11\x11\x11"), BLOCK_SIZE)
if err == nil {
panic(fmt.Sprint("process error"))
}

})

t.Run("Unpads error format", func(t *testing.T) {
_, err := Unpad([]byte("12345678901\x06\x06\x06\x06\x06"), BLOCK_SIZE)
if err == nil {
panic(fmt.Sprint("process error"))
}

})

t.Run("Handles long", func(t *testing.T) {
longStr := []byte("123456789012345678901234567890123456789012345678901234567890")
padded, _ := Pad(longStr, BLOCK_SIZE)
Expand Down