YouChuKoffee/app/utils/encrypt/encrypt.go

80 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package encrypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"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
}
// =================== 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)]
}