/**
  @author: yaoyuliang
**/
package utils

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"strings"
)

func DescrySignPhone(phone string) string {

	phoneSignStr, _ := AesDecryptBySaas([]byte(phone), []byte("dbcaespassword93"))
	return phoneSignStr
}

func AesDecryptBySaas(crypted, key []byte) (string, error) {
	ciphertext := strings.Replace(string(crypted), " ", "", -1)
	cryptedOri, err := base64.StdEncoding.DecodeString(ciphertext)

	if err != nil {
		return "", err
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(cryptedOri))
	// 修复过长手机号问题
	if len(cryptedOri)%block.BlockSize() != 0 {
		return string(crypted), nil
	}
	blockMode.CryptBlocks(origData, cryptedOri)
	origData = PKCS7UnPadding(origData)
	return string(origData), nil
}

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