qnc-server-old/utils/antifraud.go

90 lines
2.5 KiB
Go
Raw Normal View History

2024-09-14 10:48:09 +08:00
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"math"
)
// 对明文进行填充
func Padding(plainText []byte, blockSize int) []byte {
//计算要填充的长度
n := blockSize - len(plainText)%blockSize
//对原来的明文填充n个n
temp := bytes.Repeat([]byte{byte(n)}, n)
plainText = append(plainText, temp...)
return plainText
}
// 对密文删除填充
func UnPadding(cipherText []byte) []byte {
//取出密文最后一个字节end
end := cipherText[len(cipherText)-1]
//删除填充
cipherText = cipherText[:len(cipherText)-int(end)]
return cipherText
}
// AEC加密CBC模式
func AES_CBC_Encrypt(plainText []byte, key []byte) []byte {
//指定加密算法返回一个AES算法的Block接口对象
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
//进行填充
plainText = Padding(plainText, block.BlockSize())
//指定初始向量vi,长度和block的块尺寸一致
iv := []byte("0000000000000000")
//指定分组模式返回一个BlockMode接口对象
blockMode := cipher.NewCBCEncrypter(block, iv)
//加密连续数据库
cipherText := make([]byte, len(plainText))
blockMode.CryptBlocks(cipherText, plainText)
//返回base64密文
return cipherText
}
// AEC解密CBC模式
func AES_CBC_Decrypt(cipherText []byte, key []byte) []byte {
//指定解密算法返回一个AES算法的Block接口对象
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
//指定初始化向量IV,和加密的一致
iv := []byte("0000000000000000")
//指定分组模式返回一个BlockMode接口对象
blockMode := cipher.NewCBCDecrypter(block, iv)
//解密
plainText := make([]byte, len(cipherText))
blockMode.CryptBlocks(plainText, cipherText)
//删除填充
plainText = UnPadding(plainText)
return plainText
}
// GenerateRandomString 生成一个32位的随机字符串订单号
func GenerateRandomString() (string, error) {
// 创建一个16字节的数组
bytes := make([]byte, 16)
// 读取随机字节到数组中
if _, err := rand.Read(bytes); err != nil {
return "", err
}
// 将字节数组编码为16进制字符串
return hex.EncodeToString(bytes), nil
}
// 定义一个函数,将分数从原始范围转换到 0-100 的范围
func ConvertScore(originalScore, oldMin, oldMax float64) int {
newMin := 0.0
newMax := 100.0
Score := ((originalScore - oldMin) * (newMax - newMin) / (oldMax - oldMin)) + newMin
newScore := int(math.Round(100 - Score))
return newScore
}