summaryrefslogtreecommitdiff
path: root/pkg/scrypto/pkcs5.go
blob: b41c564cd674112bf3223af3d54161a4d46f883a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package scrypto

import (
	"bytes"
	"fmt"
)

func PadPKCS5(data []byte, blockSize int) []byte {
	paddingSize := blockSize - len(data)%blockSize
	padding := bytes.Repeat([]byte{byte(paddingSize)}, paddingSize)

	return append(data, padding...)
}

func UnpadPKCS5(data []byte, blockSize int) ([]byte, error) {
	dataSize := len(data)
	if dataSize%blockSize != 0 {
		return nil, fmt.Errorf("truncated data")
	}

	if len(data) == 0 {
		return data, nil
	} else {
		paddingSize := int(data[dataSize-1])
		if paddingSize > dataSize || paddingSize > blockSize {
			return nil, fmt.Errorf("invalid padding size %d", paddingSize)
		}

		return data[:dataSize-paddingSize], nil
	}
}