//go:build amd64

package tool

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"

	"github.com/chenzhuoyu/base64x"
)

// ParseTokenWithAes256 模拟Phalcon解密token
func ParseTokenWithAes256(token, key string) ([]byte, error) {
	if token == "" {
		return nil, fmt.Errorf(`ParseTokenWithAes256 error: token is empty`)
	}
	decryptString, err := base64x.JSONStdEncoding.DecodeString(token)
	if err != nil {
		return nil, fmt.Errorf(`base64_decode: %#v`, err)
	}
	k := make([]byte, 32)
	ky := []byte(key)
	for i, v := range ky {
		k[i] = v
	}
	cb, err := aes.NewCipher(k)
	if err != nil {
		return nil, fmt.Errorf(`aes.NewCipher: %v`, err)
	}
	//fmt.Printf("token:%s,key:%s,decryptString:%s", token, key, decryptString)

	var resp = make([]byte, len(decryptString[16:]))
	cipher.NewCFBDecrypter(cb, decryptString[0:16]).XORKeyStream(resp, decryptString[16:])

	return resp, nil
}
