package crypter

import (
	"crypto/aes"
	"crypto/cipher"
	"log"
	"encoding/base64"
)

const (
	key_text = "llx.abc.d12.bdf4"
)

var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x17, 0x18, 0x29, 0x2a, 0x3b, 0x3c, 0x0d, 0x0e, 0x0f}

//加密
func Encode(plaintext []byte, salt string) string {
	if len(plaintext) == 0 {
		return ""
	}

	// 创建加密算法aes
	strKey := salt + key_text
	strKey = strKey[:16]
	c, err := aes.NewCipher([]byte(strKey))
	if err != nil {
		log.Panic(err)
	}
	//加密字符串
	cfb := cipher.NewCFBEncrypter(c, commonIV)
	ciphertext := make([]byte, len(plaintext))
	cfb.XORKeyStream(ciphertext, plaintext)
	return base64.RawURLEncoding.EncodeToString(ciphertext)
}

//解密
func Decode(str string, salt string) []byte {
	if len(str) == 0 {
		return nil
	}
	plaintext, err := base64.RawURLEncoding.DecodeString(str)
	if err != nil {
		log.Panic(err)
	}
	// 创建加密算法aes
	strKey := salt + key_text
	strKey = strKey[:16]
	c, err := aes.NewCipher([]byte(strKey))
	if err != nil {
		log.Panic(err)
	}
	// 解密字符串
	cfbdec := cipher.NewCFBDecrypter(c, commonIV)
	plaintextCopy := make([]byte, len(plaintext))
	cfbdec.XORKeyStream(plaintextCopy, plaintext)
	return plaintextCopy
}
