package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
)

func AESCBCEncpryt(data, aesKey, iv []byte) (encryptedData []byte, err error) {
	c, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, err
	}
	cfbdec := cipher.NewCBCEncrypter(c, iv[:c.BlockSize()])
	data = PKCSPadding(data, c.BlockSize())
	encryptedData = make([]byte, len(data))
	cfbdec.CryptBlocks(encryptedData, data)
	return encryptedData, nil
}

func AESCBCDecprytJD(encryptedData, aesKey, iv []byte) (decryptedData []byte, err error) {
	c, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, err
	}
	cfbdec := cipher.NewCBCDecrypter(c, iv[:c.BlockSize()])
	decryptedData = make([]byte, len(encryptedData))
	cfbdec.CryptBlocks(decryptedData, encryptedData)

	//decryptedData = PKCSUnPadding(decryptedData)
	return decryptedData, nil
}

func AESCBCDecpryt(encryptedData, aesKey, iv []byte) (decryptedData []byte, err error) {
	c, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, err
	}
	cfbdec := cipher.NewCBCDecrypter(c, iv[:c.BlockSize()])
	decryptedData = make([]byte, len(encryptedData))
	cfbdec.CryptBlocks(decryptedData, encryptedData)

	decryptedData = PKCSUnPadding(decryptedData)
	return decryptedData, nil
}

// AESCBC16Decrypt 抖音十六位解密
func AESCBC16Decrypt(key, iv, src []byte) ([]byte, error) {
	decrypted := make([]byte, len(src))
	var aesBlockDecrypt cipher.Block
	aesBlockDecrypt, err := aes.NewCipher(key)
	if err != nil {
		println(err.Error())
		return nil, err
	}
	aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, iv)
	aesDecrypt.CryptBlocks(decrypted, src)
	return decrypted[:len(decrypted)-int(decrypted[len(decrypted)-1])], err
}

func PKCSUnPadding(originData []byte) []byte {
	length := len(originData)
	unpadding := int(originData[length-1])
	originData = originData[:(length - unpadding)]
	return originData
}

func PKCSPadding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}
