2024-06-17 14:18:39 +08:00
|
|
|
|
package encrypt
|
|
|
|
|
|
|
|
|
|
import (
|
2024-06-19 18:32:34 +08:00
|
|
|
|
"bytes"
|
|
|
|
|
"crypto/aes"
|
|
|
|
|
"crypto/cipher"
|
|
|
|
|
"encoding/base64"
|
2024-06-17 14:18:39 +08:00
|
|
|
|
"math/rand"
|
|
|
|
|
"unsafe"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const lettersString = "0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
|
|
|
|
|
|
|
|
|
|
// 字符串长度
|
|
|
|
|
const number = 16
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
16位码,前15位随机字符串,最后一位通过前15位字符串计算校验生成
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
func LotteryEncryptEncode() string {
|
|
|
|
|
b := make([]byte, number)
|
|
|
|
|
var sum byte
|
|
|
|
|
for i := 0; i < number-1; i++ {
|
|
|
|
|
b[i] = lettersString[rand.Int63()%int64(len(lettersString))]
|
|
|
|
|
sum += b[i]
|
|
|
|
|
}
|
|
|
|
|
b[number-1] = lettersString[sum%byte(len(lettersString))]
|
|
|
|
|
return *(*string)(unsafe.Pointer(&b))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func LotteryEncryptDecode(str string) bool {
|
|
|
|
|
var sum byte
|
|
|
|
|
for i := 0; i < len(str)-1; i++ {
|
|
|
|
|
sum += str[i]
|
|
|
|
|
}
|
|
|
|
|
if lettersString[sum%byte(len(lettersString))] != str[len(str)-1] {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|
2024-06-19 18:32:34 +08:00
|
|
|
|
|
|
|
|
|
// =================== CBC ======================
|
|
|
|
|
func AesEncryptCBC(origData []byte, key []byte) (str string) {
|
|
|
|
|
// 分组秘钥
|
|
|
|
|
// NewCipher该函数限制了输入k的长度必须为16, 24或者32
|
|
|
|
|
block, _ := aes.NewCipher(key)
|
|
|
|
|
blockSize := block.BlockSize() // 获取秘钥块的长度
|
|
|
|
|
origData = pkcs5Padding(origData, blockSize) // 补全码
|
|
|
|
|
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
|
|
|
|
|
encrypted := make([]byte, len(origData)) // 创建数组
|
|
|
|
|
blockMode.CryptBlocks(encrypted, origData) // 加密
|
|
|
|
|
|
|
|
|
|
return base64.StdEncoding.EncodeToString(encrypted)
|
|
|
|
|
}
|
|
|
|
|
func AesDecryptCBC(data string, key []byte) (decrypted []byte) {
|
|
|
|
|
encrypted, err := base64.StdEncoding.DecodeString(data)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
block, _ := aes.NewCipher(key) // 分组秘钥
|
|
|
|
|
blockSize := block.BlockSize() // 获取秘钥块的长度
|
|
|
|
|
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) // 加密模式
|
|
|
|
|
decrypted = make([]byte, len(encrypted)) // 创建数组
|
|
|
|
|
blockMode.CryptBlocks(decrypted, encrypted) // 解密
|
|
|
|
|
decrypted = pkcs5UnPadding(decrypted) // 去除补全码
|
|
|
|
|
return decrypted
|
|
|
|
|
}
|
|
|
|
|
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
|
|
|
|
|
padding := blockSize - len(ciphertext)%blockSize
|
|
|
|
|
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
|
|
|
|
return append(ciphertext, padtext...)
|
|
|
|
|
}
|
|
|
|
|
func pkcs5UnPadding(origData []byte) []byte {
|
|
|
|
|
length := len(origData)
|
|
|
|
|
unpadding := int(origData[length-1])
|
|
|
|
|
return origData[:(length - unpadding)]
|
|
|
|
|
}
|