2 Star 0 Fork 1

web-bird/bird

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
encrypts.go 2.35 KB
一键复制 编辑 原始数据 按行查看 历史
悟道人 提交于 2020-11-12 15:15 +08:00 . 保存
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"fmt"
"sync/atomic"
"time"
)
//sha1加密
func Sha1(a ...interface{}) string {
sha := sha1.New()
sha.Write([]byte(fmt.Sprint(a...)))
return hex.EncodeToString(sha.Sum([]byte("")))
}
//sha1加密
func Sha256(a ...interface{}) string {
sha := sha256.New()
sha.Write([]byte(fmt.Sprint(a...)))
return hex.EncodeToString(sha.Sum([]byte("")))
}
//md5加密
func Md5(a ...interface{}) string {
object := md5.New()
object.Write([]byte(fmt.Sprint(a...)))
cipherStr := object.Sum(nil)
return hex.EncodeToString(cipherStr)
}
//crc校验码
func CRC16(data []byte) []byte {
var crc16 uint16 = 0xffff
l := len(data)
for i := 0; i < l; i++ {
crc16 ^= uint16(data[i])
for j := 0; j < 8; j++ {
if crc16&0x0001 > 0 {
crc16 = (crc16 >> 1) ^ 0xA001
} else {
crc16 >>= 1
}
}
}
packet := make([]byte, 2)
packet[0] = byte(crc16 & 0xff)
packet[1] = byte(crc16 >> 8)
return packet
}
//
var snIndex int64 = 1000
//16位
func MakeSN() string {
if snIndex > 10000000 {
atomic.StoreInt64(&snIndex, 0)
}
index := atomic.AddInt64(&snIndex, 1)
sn := time.Now().Format("0601021504") + fmt.Sprintf("%0.6X", index)
return sn[:16]
}
//AES加密
func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = pkcs7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
//AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = pkcs7UnPadding(origData)
return origData, nil
}
func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func pkcs7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/web-bird/bird.git
git@gitee.com:web-bird/bird.git
web-bird
bird
bird
ac7d4c82d0c1

搜索帮助