package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"gin-vue-admin/global"
	"strings"
)

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}
func ZEROPadding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{0}, padding) //用0去填充
	return append(ciphertext, padtext...)
}

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

//加密 aes-cbc-128
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)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

//解密 aes-cbc-128
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])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}

// 数据加密
func DataAesEncrypt(Data string) (int, string, error) {
	cert := global.GVA_CONFIG.Encrypt
	data := []byte(Data)
	xpass, err := AesEncrypt(data, []byte(cert.Key))
	if err != nil {
		return 0, "", err
	}

	pass64 := base64.StdEncoding.EncodeToString(xpass)
	return 1, pass64, nil
}

// 数据解密
func DataAesDecrypt(Data string) (int, string, error) {
	cert := global.GVA_CONFIG.Encrypt

	Data = strings.Replace(Data, " ", "", -1)
	bytesPass, err := base64.StdEncoding.DecodeString(Data)
	xpass, err := AesDecrypt(bytesPass, []byte(cert.Key))
	if err != nil {
		return 0, "", err
	}

	return 1, string(xpass[:]), nil
}

// 数据加密
func TestDataAesEncrypt(Data string) (int, string, error) {
	cert := global.GVA_CONFIG.Encrypt
	data := []byte(Data)
	xpass, err := TestAesEncrypt(data, []byte(cert.Key))
	if err != nil {
		return 0, "", err
	}

	pass64 := base64.StdEncoding.EncodeToString(xpass)
	return 1, pass64, nil
}

//加密 aes-cbc-128
func TestAesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	origData = ZEROPadding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}