package crypto

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

// aesKey 字符串AES加解密密钥
const aesKey = "AGT66VfY4SMaiT97"

// StringEncryptByAES 字符串AES加密
func StringEncryptByAES(text string) (string, error) {
	if len(text) == 0 {
		return "", nil
	}
	pass := []byte(text)
	xpass, err := aesEncryptWithSalt([]byte(aesKey), pass)
	if err == nil {
		pass64 := base64.StdEncoding.EncodeToString(xpass)
		return pass64, err
	}
	return "", err
}

// StringDecryptByAES 字符串AES解密
func StringDecryptByAES(text string) (string, error) {
	if len(text) == 0 {
		return "", nil
	}
	bytesPass, err := base64.StdEncoding.DecodeString(text)
	if err != nil {
		return "", err
	}
	var tpass []byte
	tpass, err = aesDecryptWithSalt([]byte(aesKey), bytesPass)
	if err == nil {
		result := string(tpass[:])
		return result, err
	}
	return "", err
}

// aesEncryptWithSalt AES加密
func aesEncryptWithSalt(key, plaintext []byte) ([]byte, error) {
	blockSize := aes.BlockSize
	padding := blockSize - len(plaintext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	plaintext = append(plaintext, padtext...)

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	ciphertext := make([]byte, blockSize+len(plaintext))
	iv := ciphertext[0:blockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	cbc := cipher.NewCBCEncrypter(block, iv)
	cbc.CryptBlocks(ciphertext[blockSize:], plaintext)
	return ciphertext, nil
}

// aesDecryptWithSalt AES解密
func aesDecryptWithSalt(key, ciphertext []byte) ([]byte, error) {
	blockSize := aes.BlockSize
	var block cipher.Block
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(ciphertext) < blockSize {
		return nil, fmt.Errorf("iciphertext too short")
	}
	iv := ciphertext[:blockSize]
	ciphertext = ciphertext[blockSize:]
	cbc := cipher.NewCBCDecrypter(block, iv)
	cbc.CryptBlocks(ciphertext, ciphertext)
	length := len(ciphertext)
	unpadding := int(ciphertext[len(ciphertext)-1])
	ciphertext = ciphertext[:(length - unpadding)]
	return ciphertext, nil
}
