package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
)

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

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

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

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

func AesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	tmpiv := make([]byte, blockSize)
	//blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	blockMode := cipher.NewCBCEncrypter(block, tmpiv)
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)

	return crypted, nil
}

func AesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	//blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	tmpiv := make([]byte, blockSize)
	blockMode := cipher.NewCBCDecrypter(block, tmpiv)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}

func AesEncryptBase64Key(origData []byte, base64key string) ([]byte, error) {
	key, keyerr := base64.StdEncoding.DecodeString(base64key)
	if keyerr != nil {
		return nil, keyerr
	}

	return AesEncrypt(origData, key)
}

func AesDecryptBase64Key(crypted []byte, base64key string) ([]byte, error) {
	key, keyerr := base64.StdEncoding.DecodeString(base64key)
	if keyerr != nil {
		return nil, keyerr
	}
	fmt.Println("key:", key)

	return AesDecrypt(crypted, key)
}
