This commit is contained in:
jiayuqi7813
2022-05-21 23:29:23 +08:00
parent b8859af6d8
commit 7cb171bc90
83 changed files with 1687 additions and 0 deletions

55
tools/aes.go Normal file
View File

@@ -0,0 +1,55 @@
package tools
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
var Aeskey = []byte("snowywar12345678") //aeskey
//@brief:填充明文
func PKCS5Padding(plaintext []byte, blockSize int) []byte{
padding := blockSize-len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)},padding)
return append(plaintext,padtext...)
}
//@brief:去除填充数据
func PKCS5UnPadding(origData []byte) []byte{
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
//@brief:AES加密
func AesEncrypt(origData, key []byte) ([]byte, error){
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//AES分组长度为128位所以blockSize=16单位字节
blockSize := block.BlockSize()
origData = PKCS5Padding(origData,blockSize)
blockMode := cipher.NewCBCEncrypter(block,key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted,origData)
return crypted, nil
}
//@brief:AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//AES分组长度为128位所以blockSize=16单位字节
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}

14
tools/checkid.go Normal file
View File

@@ -0,0 +1,14 @@
package tools
import "regexp"
// CheckID 验证id是否为非负正整数。
func CheckID(id string) bool {
if id == "1" {
return false
}
pattern := `^[1-9]\d*$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(id)
}

13
tools/md5.go Normal file
View File

@@ -0,0 +1,13 @@
package tools
import (
"crypto/md5"
"encoding/hex"
)
func MD5(v string)string{
d := []byte(v)
m := md5.New()
m.Write(d)
return hex.EncodeToString(m.Sum(nil))
}

35
tools/token.go Normal file
View File

@@ -0,0 +1,35 @@
package tools
import (
"crypto/rand"
"fmt"
"io"
"time"
)
// Random 生成随机数。
func Random() []byte {
b := make([]byte, 32)
//ReadFull从rand.Reader精确地读取len(b)字节数据填充进b
//rand.Reader是一个全局、共享的密码用强随机数生成器
if _, err := io.ReadFull(rand.Reader, b); err != nil {
fmt.Printf("random number generation error: %v", err)
}
return b
}
// Token 生成随机token。
func Token() string {
b := Random()[:16]
return fmt.Sprintf("%x", b)
}
// Timestamp 用于获取当前10位数时间戳。
func Timestamp() int {
// time_zone := time.FixedZone("UTC", 0)
// t := time.Now().In(time_zone).Unix()
t := time.Now().Unix()
return int(t)
}