package sm4

import (
	"bytes"
	"fmt"
)

func PKCS5Padding(src []byte, blockSize int) []byte {
	padding := blockSize - len(src)%blockSize
	padBytes := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(src, padBytes...)
}

func PKCS5UnPadding(src []byte) []byte {
	length := len(src)
	unPadding := int(src[length-1])
	return src[:(length - unPadding)]
}

func PKCS7Padding(src []byte) []byte {
	padding := BlockSize - len(src)%BlockSize
	padBytes := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(src, padBytes...)
}

func PKCS7UnPadding(src []byte) ([]byte, error) {
	length := len(src)
	unPadding := int(src[length-1])
	if unPadding > BlockSize || unPadding == 0 {
		return nil, fmt.Errorf("invalid pkcs7 padding (unPadding > BlockSize || unPadding == 0)")
	}
	pad := src[len(src)-unPadding:]
	for i := 0; i < unPadding; i++ {
		if pad[i] != byte(unPadding) {
			return nil, fmt.Errorf("invalid pkcs7 padding (pad[i] != unPadding)")
		}
	}
	return src[:(length - unPadding)], nil
}
