49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package cryptojs
|
|
|
|
import (
|
|
"fmt"
|
|
"bytes"
|
|
)
|
|
|
|
// Appends padding.
|
|
func pkcs7Pad(data []byte, blocklen int) ([]byte, error) {
|
|
if blocklen <= 0 {
|
|
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
|
|
}
|
|
padlen := uint8(1)
|
|
for ((len(data) + int(padlen)) % blocklen) != 0 {
|
|
padlen++
|
|
}
|
|
|
|
if int(padlen) > blocklen {
|
|
panic(fmt.Sprintf("generated invalid padding length %v for block length %v", padlen, blocklen))
|
|
}
|
|
pad := bytes.Repeat([]byte{byte(padlen)}, int(padlen))
|
|
return append(data, pad...), nil
|
|
}
|
|
|
|
// Returns slice of the original data without padding.
|
|
func pkcs7Unpad(data []byte, blocklen int) ([]byte, error) {
|
|
if blocklen <= 0 {
|
|
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
|
|
}
|
|
if len(data)%blocklen != 0 || len(data) == 0 {
|
|
return nil, fmt.Errorf("invalid data len %d", len(data))
|
|
}
|
|
|
|
padlen := int(data[len(data)-1])
|
|
if padlen > blocklen || padlen == 0 {
|
|
// Not padded
|
|
return data, nil
|
|
}
|
|
// check padding
|
|
pad := data[len(data)-padlen:]
|
|
for i := 0; i < padlen; i++ {
|
|
if pad[i] != byte(padlen) {
|
|
return data, nil
|
|
}
|
|
}
|
|
|
|
return data[:len(data)-padlen], nil
|
|
}
|