first commit
This commit is contained in:
@@ -0,0 +1,707 @@
|
||||
package baseutils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/des"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"math/big"
|
||||
|
||||
"github.com/micro/go-micro/util/log"
|
||||
)
|
||||
|
||||
const (
|
||||
public_key_99 = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDf5W7uZQbl+XlrTxLDpIEhuE5U\njpmZ2DTiwDfjzSdunEorF1jFgqZ/bRKJXOVSXd5R0LktMri+eyyFgncpw1cdzBS1\ngYd7xjS8x/naOCXJeiWzQaZClQmDA8S1hOxXnsynyLlngvZdZQA57noHcsGV2+/E\nSIvfsLmljFwFjjqwTQIDAQAB\n-----END PUBLIC KEY-----\n"
|
||||
public_key_189 = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7Czt3VSBlM6KjpJYBfVE\nR9G7t9XeRwHxvx/NFLCIuJqL3KoiEVwfVW2ZRyKcrYR8y92hC9ojyk6Xm/O8WVVK\n+Ly9ruBjSjWG7nG1DrPZIGGuJI2Uc9yXvg7vSBmoNo/JH6WwVGQPsWknOe/jnAzs\n4OuTRi0A5DeSJclENnVth6Xi9lke50M9eS1S3Xy9GPSEbLg5CGG/E9r04p/SvP4g\n9UcBYyj21EvpIrWei6QyC2b9wbJosc+r8opF5LzTab45NM2suvTNIPdJVXVjGaWo\n+ZN1tK9PRKHTIabJPmS3eYyIl56KR1o7IRd71iQGN/omcJKfjlCcF3x2Gyto0o+E\nWwIDAQAB\n-----END PUBLIC KEY-----\n"
|
||||
public_key_190 = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA21WeytqtK3+fBi3AistJ\n4Zt9WIDaMadUSEPT+nmUYH8KtaWYZnl99fnAbs+hhcsf7ziE57KKfPW9VbMk2D5j\nKnOld18BcWIWb/obhGtJoTceA6J/cXKvEXkD1SMM0ZpadVK12rJlNgozV2hc3TsV\n0wteK9EYennlQot/pjIniAOSyUzeROmMvkzf53v3syzwuA3CQipdoAO3pNN86urk\ntiRb+HtQbKjeahHAEIws4XV4okSRGrf9DQeLzObxaFl6rpqxSBMl+HfZEL3rBvIW\ns9+dSb5Y56Kq32MMVfKkQXZ+awU+DyCyv7KbAyaDX/LCzWP7USTWsgcQsE+BoxMM\nSwIDAQAB\n-----END PUBLIC KEY-----\n"
|
||||
public_key_133 = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWpUR3ZA8MCyCdt3RxJo\nlrJ/trIZq5vJxM2WYfQi4UOnWrLDTquI9EcZ2NLg1XzslxN0i/gh7CAU35ewHM4m\nLyfKJPTYlJL5ncjBpBTQuOdg2BXfU6kR1dgHyvaCcIS76CWknBu5NpZ1xL5DVZdW\nW1xCIgkCNfalWVAD1dX6Z4Dr1Rzqx20D2Oufl7RSmXGffDUrLvMkSeD90JtWK6Ax\ndBi2b8CFPqn1/6heq4oU4nhcArDKxq/UUO5aaXHCIOcv5vpLeBI1850gZzTJl0En\n42nkeb8yVf/4xfpLEzxkKlZWqOXxdkcsWj/hjYgW5A5Yq8KkoyugVusLUEyG2uBZ\nBwIDAQAB\n-----END PUBLIC KEY-----"
|
||||
public_key_133_hex = "BD6A54477640F0C0B209DB7747126896B27FB6B219AB9BC9C4CD9661F422E143A75AB2C34EAB88F44719D8D2E0D57CEC9713748BF821EC2014DF97B01CCE262F27CA24F4D89492F99DC8C1A414D0B8E760D815DF53A911D5D807CAF6827084BBE825A49C1BB9369675C4BE435597565B5C4222090235F6A5595003D5D5FA6780EBD51CEAC76D03D8EB9F97B45299719F7C352B2EF32449E0FDD09B562BA0317418B66FC0853EA9F5FFA85EAB8A14E2785C02B0CAC6AFD450EE5A6971C220E72FE6FA4B781235F39D206734C9974127E369E479BF3255FFF8C5FA4B133C642A5656A8E5F176472C5A3FE18D8816E40E58ABC2A4A32BA056EB0B504C86DAE05907"
|
||||
public_key_135 = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtXkUc/36zOQmBYQBthJa\nPW/t12x90bBCanPYpBgrKeptBfT16NmaTT0cPlzzyMs83fk1ZDyU04kniBsUTQTz\nEPEzB9GuY6EAonl6cUwNHipaDvd5/D1vfTwzlidr8n2m1m4mlqZVfv1LYZDHJolN\nNc5VnhR5abrASv67DjojWyx5WsapgY4UozpEaPj/ar6KVKdBgAQr8P04Qn9wtoG5\nQxoJnndGGNRV8U0fdRIVd9rmbDhToqqcTw+cIhpm9kpG1faLDVDyLH5PoNhASLL5\nF59LhkQqJyDI/ie8aMXGOE3MM2+XkU8niLkF5f6Yxbt1RIiw9rCUIbsnv/UY7w6S\nmQIDAQAB\n-----END PUBLIC KEY-----"
|
||||
public_key_135_hex = "B5791473FDFACCE426058401B6125A3D6FEDD76C7DD1B0426A73D8A4182B29EA6D05F4F5E8D99A4D3D1C3E5CF3C8CB3CDDF935643C94D38927881B144D04F310F13307D1AE63A100A2797A714C0D1E2A5A0EF779FC3D6F7D3C3396276BF27DA6D66E2696A6557EFD4B6190C726894D35CE559E147969BAC04AFEBB0E3A235B2C795AC6A9818E14A33A4468F8FF6ABE8A54A74180042BF0FD38427F70B681B9431A099E774618D455F14D1F75121577DAE66C3853A2AA9C4F0F9C221A66F64A46D5F68B0D50F22C7E4FA0D84048B2F9179F4B86442A2720C8FE27BC68C5C6384DCC336F97914F2788B905E5FE98C5BB754488B0F6B09421BB27BFF518EF0E9299"
|
||||
public_key_125_hex = "D8D2AE73FF601B93B1471B35870A1B59D7649EEA815CDD8CE5496BBD0C6CFE19C0E082F4E513B615C6030CCFCE3153E25AA00E8156D0311AF72ABBB9BBEC8B1D3751592234B1A621CA774E2EC50047A93FA0BC60DF0C10E8A65C3B29D13167EC217FC6A29034494870705CBF4AC929FBA0E1E656A8F8B50E779AD89BB4EEF6FF"
|
||||
public_key_182_hex = "C8930AB6E688F68513682FA555E1A3C175867CDC4AAE1D054F75134D1553D9E4A1BBC846FBAEE947E1515363365185AEB39C9DD5B76BF8ADE21233E27728BC0ED8C465CCC7DBABC7EBE08B1FA23A89098D7730C31FBE375745A9AA717D7F3DE5FB8126B6D6B2B9EB1643346F00EBE3A2AA915A417B263E4026FEF4BFA91B81B035DE224857E87FB292FB9AFBAC45725D968068385963E3CDB0162C901D0921030515D1CA1E079129DD585969EF6CBABBE72E287D9A9F757FAE91543F5AADD96777BE49D1CEF58669250DB4B992C01AFE22AF5DDDB0147BD5C8B373F39381A1E914078050239D490B6FC02E68B61A81BCE0ED9710BC84481273E32ED89ACD5211"
|
||||
)
|
||||
|
||||
// Rsa的publicKey -- 135
|
||||
var publicKey = []byte(`-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtXkUc/36zOQmBYQBthJa
|
||||
PW/t12x90bBCanPYpBgrKeptBfT16NmaTT0cPlzzyMs83fk1ZDyU04kniBsUTQTz
|
||||
EPEzB9GuY6EAonl6cUwNHipaDvd5/D1vfTwzlidr8n2m1m4mlqZVfv1LYZDHJolN
|
||||
Nc5VnhR5abrASv67DjojWyx5WsapgY4UozpEaPj/ar6KVKdBgAQr8P04Qn9wtoG5
|
||||
QxoJnndGGNRV8U0fdRIVd9rmbDhToqqcTw+cIhpm9kpG1faLDVDyLH5PoNhASLL5
|
||||
F59LhkQqJyDI/ie8aMXGOE3MM2+XkU8niLkF5f6Yxbt1RIiw9rCUIbsnv/UY7w6S
|
||||
mQIDAQAB
|
||||
-----END PUBLIC KEY-----`)
|
||||
|
||||
var cdnRsaPubKey = []byte(`-----BEGIN PUBLIC KEY-----
|
||||
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/7f+16ihQn5yJ7YP6f92oiBQ1
|
||||
1ETphNU6mK2OlBDxFF7dU3iQ4QRWGQsi5uUAZFXvxsEuQf2phfOPu8chPsuBDjBT
|
||||
1LjXT/vHC0YAq9coICMir84UBgRmMSYb1e49RHIQgv6rdDQNc2RdwNAqKTuWK51H
|
||||
5KZBAL11JN4A2dO1wQIDAQAB
|
||||
-----END PUBLIC KEY-----`)
|
||||
|
||||
// encAesKeyPublicKey 这个是用来加密EncryptUserInfo Key的rsa公钥
|
||||
var encAesKeyPublicKey = []byte(`-----BEGIN PUBLIC KEY-----
|
||||
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDoqn5y8C1D0g8LVr/LSmCBiNJC
|
||||
4TdPsHa+qWBuq/xEhv01MVzIoN5Vc8UZ0qLjDeWh462Ou2Ps6E6O1C+VSTBxtLrp
|
||||
zBOxB/iAUKgw5we4G8kNijeVumVro/AovUeqUJRrMVkSBMbp/O1WZfiK7bQN0UxF
|
||||
zpQe0j8HZ9hwGWnjSQIDAQAB
|
||||
-----END PUBLIC KEY-----`)
|
||||
|
||||
// AesEncryptKeyBytes Aes加密
|
||||
func AesEncryptKeyBytes(orig []byte, key []byte) []byte {
|
||||
// 转成字节数组
|
||||
// origData := []byte(orig)
|
||||
// 分组秘钥
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
fmt.Println("AesEncryptKeyBytes - ", err.Error())
|
||||
return []byte{}
|
||||
}
|
||||
// 获取秘钥块的长度
|
||||
blockSize := block.BlockSize()
|
||||
// 补全码
|
||||
orig = PKCS7Padding(orig, blockSize)
|
||||
// 加密模式
|
||||
blockMode := cipher.NewCBCEncrypter(block, key)
|
||||
// 创建数组
|
||||
cryted := make([]byte, len(orig))
|
||||
// 加密
|
||||
blockMode.CryptBlocks(cryted, orig)
|
||||
// return base64.StdEncoding.EncodeToString(cryted)
|
||||
return cryted
|
||||
}
|
||||
|
||||
// AesEncrypt Aes加密
|
||||
func AesEncrypt(orig []byte, key []byte) []byte {
|
||||
// 转成字节数组
|
||||
// origData := []byte(orig)
|
||||
// if len(key) > 16 {
|
||||
// key = key[:16]
|
||||
// }
|
||||
return AesEncryptKeyBytes(orig, key)
|
||||
}
|
||||
|
||||
// AesDecryptByteKey Aes CBC解密
|
||||
func AesDecryptByteKey(cryted []byte, key []byte) ([]byte, error) {
|
||||
if len(cryted) <= 0 || len(key) <= 0 {
|
||||
return []byte{}, errors.New("AesDecryptByteKey err: len(cryted) <= 0 || len(key) <= 0")
|
||||
}
|
||||
// 分组秘钥
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
// 获取秘钥块的长度
|
||||
blockSize := block.BlockSize()
|
||||
// 加密模式
|
||||
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
||||
// 创建数组
|
||||
orig := make([]byte, len(cryted))
|
||||
// 解密
|
||||
blockMode.CryptBlocks(orig, cryted)
|
||||
// 去补全码
|
||||
return PKCS7UnPadding(orig)
|
||||
}
|
||||
|
||||
// AesDecrypt aes CBC解密
|
||||
func AesDecrypt(cryted []byte, key []byte) ([]byte, error) {
|
||||
return AesDecryptByteKey(cryted, key)
|
||||
}
|
||||
|
||||
// PKCS7Padding 补码
|
||||
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
|
||||
padding := blocksize - len(ciphertext)%blocksize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
// PKCS7UnPadding 去码
|
||||
func PKCS7UnPadding(origData []byte) ([]byte, error) {
|
||||
length := len(origData)
|
||||
unpadding := int(origData[length-1])
|
||||
if unpadding > length {
|
||||
fmt.Println(hex.EncodeToString(origData))
|
||||
return []byte{}, errors.New("PKCS7UnPadding err: unpadding > length")
|
||||
}
|
||||
|
||||
return origData[:(length - unpadding)], nil
|
||||
}
|
||||
|
||||
// RsaEncryptByVer 根据RsaKey 版本进行加密
|
||||
func RsaEncryptByVer(origData []byte, ver uint32) ([]byte, error) {
|
||||
var publicKey []byte
|
||||
switch ver {
|
||||
case 133: //新疆号使用
|
||||
publicKey = []byte(public_key_133)
|
||||
case 135: //国内国外
|
||||
publicKey = []byte(public_key_135)
|
||||
case 190:
|
||||
publicKey = []byte(public_key_190)
|
||||
case 189:
|
||||
publicKey = []byte(public_key_189)
|
||||
case 99:
|
||||
publicKey = []byte(public_key_99)
|
||||
|
||||
}
|
||||
|
||||
block, _ := pem.Decode(publicKey)
|
||||
if block == nil {
|
||||
return nil, errors.New("public key error")
|
||||
}
|
||||
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub := pubInterface.(*rsa.PublicKey)
|
||||
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
|
||||
}
|
||||
|
||||
// RsaEncrypt 加密
|
||||
func RsaEncrypt(origData []byte) ([]byte, error) {
|
||||
block, _ := pem.Decode(publicKey)
|
||||
if block == nil {
|
||||
return nil, errors.New("public key error")
|
||||
}
|
||||
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub := pubInterface.(*rsa.PublicKey)
|
||||
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
|
||||
}
|
||||
|
||||
// EncKeyRsaEncrypt 加密
|
||||
func EncKeyRsaEncrypt(origData []byte) ([]byte, error) {
|
||||
block, _ := pem.Decode(encAesKeyPublicKey)
|
||||
if block == nil {
|
||||
return nil, errors.New("public key error")
|
||||
}
|
||||
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub := pubInterface.(*rsa.PublicKey)
|
||||
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
|
||||
}
|
||||
|
||||
// CdnRsaEncrypt Cdn,Aes加密
|
||||
func CdnRsaEncrypt(origData []byte) ([]byte, error) {
|
||||
block, _ := pem.Decode(cdnRsaPubKey)
|
||||
if block == nil {
|
||||
return nil, errors.New("public key error")
|
||||
}
|
||||
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub := pubInterface.(*rsa.PublicKey)
|
||||
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
|
||||
}
|
||||
|
||||
// Md5Value 计算字符串的MD5值
|
||||
func Md5Value(str string) string {
|
||||
data := []byte(str)
|
||||
has := md5.Sum(data)
|
||||
md5str := fmt.Sprintf("%x", has)
|
||||
return md5str
|
||||
}
|
||||
|
||||
func MD5ToLower(str string) string {
|
||||
h := md5.New()
|
||||
h.Write([]byte(str))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func ALLGather(Data []string) string {
|
||||
var M string
|
||||
for i := 0; i < len(Data); i++ {
|
||||
M += Data[i]
|
||||
}
|
||||
return M
|
||||
}
|
||||
|
||||
func BytesToInt(bys []byte) int {
|
||||
bytebuff := bytes.NewBuffer(bys)
|
||||
var data int64
|
||||
binary.Read(bytebuff, binary.BigEndian, &data)
|
||||
return int(data)
|
||||
}
|
||||
|
||||
// Md5ValueByte 计算字节数组的MD5值
|
||||
func Md5ValueByte(data []byte, bUpper bool) string {
|
||||
has := md5.Sum(data)
|
||||
tmpString := "%x"
|
||||
if bUpper {
|
||||
tmpString = "%X"
|
||||
}
|
||||
md5str := fmt.Sprintf(tmpString, has)
|
||||
return md5str
|
||||
}
|
||||
|
||||
// Md5Value16 计算16为的md5值
|
||||
func Md5Value16(data []byte) [16]byte {
|
||||
return md5.Sum(data)
|
||||
}
|
||||
|
||||
// Adler32 计算Adler32
|
||||
func Adler32(adler uint32, data []byte) uint32 {
|
||||
s1 := adler & 0xffff
|
||||
s2 := (adler >> 16) & 0xffff
|
||||
|
||||
length := len(data)
|
||||
for index := 0; index < length; index++ {
|
||||
s1 = (s1 + uint32(data[index])) % 65521
|
||||
s2 = (s2 + s1) % 65521
|
||||
}
|
||||
|
||||
return (s2 << 16) + s1
|
||||
}
|
||||
|
||||
// AesEncryptECB Aes ECB模式加密
|
||||
func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
|
||||
cipher, _ := aes.NewCipher(key)
|
||||
length := (len(origData) + aes.BlockSize) / aes.BlockSize
|
||||
plain := make([]byte, length*aes.BlockSize)
|
||||
copy(plain, origData)
|
||||
pad := byte(len(plain) - len(origData))
|
||||
for i := len(origData); i < len(plain); i++ {
|
||||
plain[i] = pad
|
||||
}
|
||||
encrypted = make([]byte, len(plain))
|
||||
// 分组分块加密
|
||||
for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
||||
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
|
||||
}
|
||||
return encrypted
|
||||
}
|
||||
|
||||
// AesDecryptECB AesDecryptECB
|
||||
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
|
||||
cipher, _ := aes.NewCipher(key)
|
||||
decrypted = make([]byte, len(encrypted))
|
||||
for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
||||
cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
|
||||
}
|
||||
trim := 0
|
||||
if len(decrypted) > 0 {
|
||||
trim = len(decrypted) - int(decrypted[len(decrypted)-1])
|
||||
}
|
||||
return decrypted[:trim]
|
||||
}
|
||||
|
||||
// Sha1 计算Sha值
|
||||
func Sha1(data []byte) []byte {
|
||||
sha1 := sha1.New()
|
||||
sha1.Write(data)
|
||||
return sha1.Sum([]byte(""))
|
||||
}
|
||||
func split(buf []byte, lim int) [][]byte {
|
||||
var chunk []byte
|
||||
chunks := make([][]byte, 0, len(buf)/lim+1)
|
||||
for len(buf) >= lim {
|
||||
chunk, buf = buf[:lim], buf[lim:]
|
||||
chunks = append(chunks, chunk)
|
||||
}
|
||||
if len(buf) > 0 {
|
||||
chunks = append(chunks, buf[:])
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
// 根据Key 版本进行加密
|
||||
func RsaEncryptByVerNew(origData []byte, ver uint32) ([]byte, error) {
|
||||
publicKey := ""
|
||||
|
||||
switch ver {
|
||||
case 133:
|
||||
publicKey = public_key_133_hex
|
||||
break
|
||||
case 135:
|
||||
publicKey = public_key_135_hex
|
||||
break
|
||||
case 125:
|
||||
publicKey = public_key_125_hex
|
||||
case 182:
|
||||
publicKey = public_key_182_hex
|
||||
|
||||
}
|
||||
|
||||
bigInt := new(big.Int)
|
||||
n, ok := bigInt.SetString(publicKey, 16)
|
||||
if !ok {
|
||||
return nil, errors.New("转换失败")
|
||||
}
|
||||
|
||||
pub := &rsa.PublicKey{
|
||||
N: n,
|
||||
E: 65537,
|
||||
}
|
||||
|
||||
partLen := pub.N.BitLen()/8 - 11
|
||||
chunks := split(origData, partLen)
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for _, chunk := range chunks {
|
||||
bs, err := rsa.EncryptPKCS1v15(rand.Reader, pub, chunk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buffer.Write(bs)
|
||||
}
|
||||
|
||||
return buffer.Bytes(), nil
|
||||
}
|
||||
|
||||
// NoCompressRsaByVer NoCompressRsa 根据Key 版本进行加密
|
||||
// todo:2020/6/17 12:44 增加
|
||||
func NoCompressRsaByVer(data []byte, ver uint32) []byte {
|
||||
|
||||
retData, err := RsaEncryptByVerNew(data, ver)
|
||||
if err != nil {
|
||||
fmt.Println("NoCompressRsaByVer err == ", err.Error())
|
||||
}
|
||||
return retData
|
||||
}
|
||||
|
||||
// CompressAndRsaByVer 压缩后进行rsa加密 根据Key 版本进行加密
|
||||
// todo:2020/6/17 12:44 增加
|
||||
func CompressAndRsaByVer(data []byte, ver uint32) []byte {
|
||||
newData := CompressByteArray(data)
|
||||
retData, err := RsaEncryptByVerNew(newData, ver)
|
||||
if err != nil {
|
||||
fmt.Println("CompressAndRsaByVer err == ", err.Error())
|
||||
}
|
||||
return retData
|
||||
}
|
||||
|
||||
// NoCompressRsa NoCompressRsa
|
||||
func NoCompressRsa(data []byte) []byte {
|
||||
rsaKeySize := 2048
|
||||
rsaLen := rsaKeySize/8 - 12
|
||||
dataLen := len(data)
|
||||
|
||||
retData := make([]byte, 0)
|
||||
if dataLen <= rsaLen {
|
||||
retData, err := RsaEncrypt(data)
|
||||
if err != nil {
|
||||
log.Info("CompressAndRsa err = ", err)
|
||||
}
|
||||
|
||||
return retData
|
||||
}
|
||||
|
||||
// 分块加密
|
||||
blockCnt := dataLen / rsaLen
|
||||
if dataLen%rsaLen != 0 {
|
||||
blockCnt = blockCnt + 1
|
||||
}
|
||||
var tmpBlockCnt = blockCnt
|
||||
for tmpBlockCnt > 0 {
|
||||
startPos := (blockCnt - tmpBlockCnt) * rsaLen
|
||||
blockSize := startPos + rsaLen
|
||||
if tmpBlockCnt == 1 {
|
||||
blockSize = dataLen
|
||||
}
|
||||
|
||||
tmpBuf := make([]byte, 0)
|
||||
tmpBuf = append(tmpBuf, data[startPos:blockSize]...)
|
||||
encodedData, err := RsaEncrypt(tmpBuf)
|
||||
if err != nil {
|
||||
log.Info("CompressAndRsa err = ", err)
|
||||
}
|
||||
retData = append(retData, encodedData[0:]...)
|
||||
tmpBlockCnt = tmpBlockCnt - 1
|
||||
}
|
||||
|
||||
return retData
|
||||
}
|
||||
|
||||
// CompressAndRsa 压缩后进行rsa加密
|
||||
func CompressAndRsa(data []byte) []byte {
|
||||
newData := CompressByteArray(data)
|
||||
rsaKeySize := 2048
|
||||
rsaLen := rsaKeySize/8 - 12
|
||||
newDataLen := len(newData)
|
||||
|
||||
if newDataLen <= rsaLen {
|
||||
newData, err := RsaEncrypt(newData)
|
||||
if err != nil {
|
||||
log.Info("CompressAndRsa err = ", err)
|
||||
}
|
||||
return newData
|
||||
}
|
||||
|
||||
retData := make([]byte, 0)
|
||||
// 分块加密
|
||||
blockCnt := newDataLen / rsaLen
|
||||
if newDataLen%rsaLen != 0 {
|
||||
blockCnt = blockCnt + 1
|
||||
}
|
||||
var tmpBlockCnt = blockCnt
|
||||
for tmpBlockCnt > 0 {
|
||||
startPos := (blockCnt - tmpBlockCnt) * rsaLen
|
||||
blockSize := startPos + rsaLen
|
||||
if tmpBlockCnt == 1 {
|
||||
blockSize = newDataLen
|
||||
}
|
||||
|
||||
tmpBuf := make([]byte, 0)
|
||||
tmpBuf = append(tmpBuf, newData[startPos:blockSize]...)
|
||||
encodedData, err := RsaEncrypt(tmpBuf)
|
||||
if err != nil {
|
||||
PrintLog(err.Error())
|
||||
}
|
||||
retData = append(retData, encodedData[0:]...)
|
||||
tmpBlockCnt = tmpBlockCnt - 1
|
||||
}
|
||||
|
||||
return retData
|
||||
}
|
||||
|
||||
// CompressAes 压缩然后aes加密
|
||||
func CompressAes(aesKey []byte, data []byte) []byte {
|
||||
newData := CompressByteArray(data)
|
||||
newData = AesEncrypt(newData, aesKey)
|
||||
|
||||
return newData
|
||||
}
|
||||
|
||||
// DecryptSnsVideoData 解密视频
|
||||
func DecryptSnsVideoData(data []byte, encLen uint32, tmpKey uint64) []byte {
|
||||
aacInst := CreateISAacInst(tmpKey)
|
||||
// 解密数据
|
||||
for index := uint32(0); index < encLen; index += 8 {
|
||||
randNumber := ISAacRandom(aacInst)
|
||||
tmpBytes := UInt64ToBytes(randNumber)
|
||||
for tmpIndex := uint32(0); tmpIndex < 8; tmpIndex++ {
|
||||
realIndex := index + tmpIndex
|
||||
if realIndex >= encLen {
|
||||
return data
|
||||
}
|
||||
data[index+tmpIndex] ^= tmpBytes[tmpIndex]
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func padding(src []byte, blocksize int) []byte {
|
||||
padnum := blocksize - len(src)%blocksize
|
||||
pad := bytes.Repeat([]byte{byte(padnum)}, padnum)
|
||||
return append(src, pad...)
|
||||
}
|
||||
|
||||
func unpadding(src []byte) []byte {
|
||||
n := len(src)
|
||||
unpadnum := int(src[n-1])
|
||||
return src[:n-unpadnum]
|
||||
}
|
||||
|
||||
// PKCS5Padding PKCS5Padding
|
||||
func PKCS5Padding(cipherText []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(cipherText)%blockSize
|
||||
padText := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(cipherText, padText...)
|
||||
}
|
||||
|
||||
// PKCS5UnPadding PKCS5UnPadding
|
||||
func PKCS5UnPadding(origData []byte) []byte {
|
||||
length := len(origData)
|
||||
unpadding := int(origData[length-1])
|
||||
return origData[:(length - unpadding)]
|
||||
}
|
||||
|
||||
// EncryptDESECB ECB加密
|
||||
func EncryptDESECB(data []byte, keyByte []byte) ([]byte, error) {
|
||||
block, err := des.NewCipher(keyByte)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bs := block.BlockSize()
|
||||
//对明文数据进行补码
|
||||
data = PKCS5Padding(data, bs)
|
||||
if len(data)%bs != 0 {
|
||||
return nil, errors.New("Need a multiple of the blocksize")
|
||||
}
|
||||
out := make([]byte, len(data))
|
||||
dst := out
|
||||
for len(data) > 0 {
|
||||
//对明文按照blocksize进行分块加密
|
||||
//必要时可以使用go关键字进行并行加密
|
||||
block.Encrypt(dst, data[:bs])
|
||||
data = data[bs:]
|
||||
dst = dst[bs:]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DecryptDESECB DesEC解密
|
||||
func DecryptDESECB(data []byte, key []byte) ([]byte, error) {
|
||||
if len(key) > 8 {
|
||||
key = key[:8]
|
||||
}
|
||||
block, err := des.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bs := block.BlockSize()
|
||||
if len(data)%bs != 0 {
|
||||
return nil, errors.New("DecryptDES crypto/cipher: input not full blocks")
|
||||
}
|
||||
out := make([]byte, len(data))
|
||||
dst := out
|
||||
for len(data) > 0 {
|
||||
block.Decrypt(dst, data[:bs])
|
||||
data = data[bs:]
|
||||
dst = dst[bs:]
|
||||
}
|
||||
// out = PKCS5UnPadding(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Encrypt3DES 3DES加密
|
||||
// src: 8字节
|
||||
// key: 16字节
|
||||
func Encrypt3DES(srcData []byte, key []byte) ([]byte, error) {
|
||||
if len(srcData) != 8 || len(key) != 16 {
|
||||
return nil, errors.New("Encrypt3DES err: srcLen != 8 || keyLen != 16")
|
||||
}
|
||||
tmpSrcData := make([]byte, 0)
|
||||
tmpSrcData = append(tmpSrcData, srcData...)
|
||||
encData, err := EncryptDESECB(tmpSrcData, key[0:8])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decData, err := DecryptDESECB(encData, key[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encData, err = EncryptDESECB(decData[0:8], key[0:8])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return encData[0:8], err
|
||||
}
|
||||
|
||||
// Decrypt3DES Encrypt3DES 3DES解密
|
||||
func Decrypt3DES(src []byte, key []byte) []byte {
|
||||
block, _ := des.NewTripleDESCipher(key)
|
||||
blockmode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()])
|
||||
blockmode.CryptBlocks(src, src)
|
||||
src = unpadding(src)
|
||||
return src
|
||||
}
|
||||
|
||||
// AesEncryptECBTest Aes ECB模式加密
|
||||
func AesEncryptECBTest(origData []byte, key []byte, pad byte) (encrypted []byte) {
|
||||
cipher, _ := aes.NewCipher(key)
|
||||
length := (len(origData) + aes.BlockSize) / aes.BlockSize
|
||||
plain := make([]byte, length*aes.BlockSize)
|
||||
copy(plain, origData)
|
||||
for i := len(origData); i < len(plain); i++ {
|
||||
plain[i] = pad
|
||||
}
|
||||
encrypted = make([]byte, len(plain))
|
||||
// 分组分块加密
|
||||
for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
|
||||
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
|
||||
}
|
||||
return encrypted
|
||||
}
|
||||
|
||||
// CalcMsgCrc calc msg hash
|
||||
func CalcMsgCrc(data []byte) int {
|
||||
salt1 := [16]byte{0x5c, 0x50, 0x7b, 0x6b, 0x65, 0x4a, 0x13, 0x09, 0x45, 0x58, 0x7e, 0x11, 0x0c, 0x1f, 0x68, 0x79}
|
||||
salt2 := [16]byte{0x36, 0x3a, 0x11, 0x01, 0x0f, 0x20, 0x79, 0x63, 0x2f, 0x32, 0x14, 0x7b, 0x66, 0x75, 0x02, 0x13}
|
||||
pad1 := [0x30]byte{
|
||||
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
|
||||
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
|
||||
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
|
||||
}
|
||||
pad2 := [0x30]byte{
|
||||
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
|
||||
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
|
||||
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
|
||||
}
|
||||
md5hash := md5.Sum(data)
|
||||
hashstr := hex.EncodeToString(md5hash[:])
|
||||
hash1Data := make([]byte, 16)
|
||||
copy(hash1Data, salt1[:])
|
||||
hash1Data = append(hash1Data, pad1[:]...)
|
||||
hash1 := sha1.New()
|
||||
hash1.Write(hash1Data)
|
||||
hash1.Write([]byte(hashstr))
|
||||
h1 := hash1.Sum(nil)
|
||||
hash2Data := make([]byte, 16)
|
||||
copy(hash2Data, salt2[:])
|
||||
hash2Data = append(hash2Data, pad2[:]...)
|
||||
hash2 := sha1.New()
|
||||
hash2.Write(hash2Data)
|
||||
hash2.Write(h1)
|
||||
h2 := hash2.Sum(nil)
|
||||
var b1, b2, b3 byte
|
||||
size := len(h2)
|
||||
for i := 0; i < size-2; i++ {
|
||||
b1 = h2[i+0] - b1*0x7d
|
||||
b2 = h2[i+1] - b2*0x7d
|
||||
b3 = h2[i+2] - b3*0x7d
|
||||
}
|
||||
return (int(0x21) << 24) | ((int(b3) & 0x7f) << 16) | ((int(b2) & 0x7f) << 8) | (int(b1) & 0x7f)
|
||||
}
|
||||
|
||||
func GetCRC32String(msg string) uint32 {
|
||||
v := []byte(msg)
|
||||
return GetCRC32(v)
|
||||
}
|
||||
|
||||
func GetCRC32(data []byte) uint32 {
|
||||
return crc32.ChecksumIEEE(data)
|
||||
}
|
||||
|
||||
// 移位操作
|
||||
func EncInt(d int64) int64 {
|
||||
a, b := int64(0), int64(0)
|
||||
for i := 0; i < 16; i++ {
|
||||
a |= ((1 << (2 * i)) & d) << (2 * i)
|
||||
b |= ((1 << (2*i + 1)) & d) << (2*i + 1)
|
||||
}
|
||||
return a | b
|
||||
}
|
||||
|
||||
func IOSGetCidMd5(DeviceId, Cid string) string {
|
||||
Md5Data := MD5ToLower(DeviceId + Cid)
|
||||
return "A136" + Md5Data[5:]
|
||||
}
|
||||
|
||||
func IOSGetCid(s int) string {
|
||||
M := inttobytes(s >> 12)
|
||||
return hex.EncodeToString(M)
|
||||
}
|
||||
|
||||
func inttobytes(n int) []byte {
|
||||
x := int32(n)
|
||||
bytesBuffer := bytes.NewBuffer([]byte{})
|
||||
binary.Write(bytesBuffer, binary.BigEndian, x)
|
||||
return bytesBuffer.Bytes()
|
||||
}
|
||||
|
||||
func IOSUuid(DeviceId string) (uuid1 string, uuid2 string) {
|
||||
Md5DataA := MD5ToLower(DeviceId + "SM2020032204320")
|
||||
//"b58b9b87-5124-4907-8c92-d8ad59ee0430"
|
||||
fmt.Println("Md5DataA", string(Md5DataA))
|
||||
uuid1 = fmt.Sprintf("%s-%s-%s-%s-%s", Md5DataA[0:8], Md5DataA[2:6], Md5DataA[3:7], Md5DataA[1:5], Md5DataA[20:32])
|
||||
Md5DataB := MD5ToLower(DeviceId + "BM2020032204321")
|
||||
uuid2 = fmt.Sprintf("%s-%s-%s-%s-%s", Md5DataB[0:8], Md5DataB[2:6], Md5DataB[3:7], Md5DataB[1:5], Md5DataB[20:32])
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package baseutils
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/micro/go-micro/util/log"
|
||||
)
|
||||
|
||||
// ReadFile ReadFile
|
||||
func ReadFile(filePth string) ([]byte, error) {
|
||||
f, err := os.Open(filePth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return ioutil.ReadAll(f)
|
||||
}
|
||||
|
||||
// WriteToFile WriteToFile
|
||||
func WriteToFile(data []byte, fileName string) {
|
||||
err := ioutil.WriteFile(fileName, data, 0666) //写入文件(字节数组)
|
||||
if err != nil {
|
||||
log.Info("WriteToFile failed: ", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package baseutils
|
||||
|
||||
const (
|
||||
msg = "a Top Secret secret"
|
||||
key = "this is my secret key"
|
||||
)
|
||||
|
||||
// RandCtx64 64位随机数
|
||||
type RandCtx64 struct {
|
||||
RandCnt uint64
|
||||
Seed [256]uint64
|
||||
MM [256]uint64
|
||||
AA uint64
|
||||
BB uint64
|
||||
CC uint64
|
||||
}
|
||||
|
||||
// CreateISAacInst 创建新的
|
||||
func CreateISAacInst(encKey uint64) *RandCtx64 {
|
||||
randCtx64 := &RandCtx64{}
|
||||
randCtx64.RandCnt = 255
|
||||
randCtx64.AA = 0
|
||||
randCtx64.BB = 0
|
||||
randCtx64.CC = 0
|
||||
Rand64Init(randCtx64, encKey)
|
||||
return randCtx64
|
||||
}
|
||||
|
||||
// Rand64Init 初始化
|
||||
func Rand64Init(randCtx64 *RandCtx64, encKey uint64) {
|
||||
a := uint64(0x9e3779b97f4a7c13)
|
||||
b := uint64(0x9e3779b97f4a7c13)
|
||||
c := uint64(0x9e3779b97f4a7c13)
|
||||
d := uint64(0x9e3779b97f4a7c13)
|
||||
e := uint64(0x9e3779b97f4a7c13)
|
||||
f := uint64(0x9e3779b97f4a7c13)
|
||||
g := uint64(0x9e3779b97f4a7c13)
|
||||
h := uint64(0x9e3779b97f4a7c13)
|
||||
|
||||
randCtx64.Seed[0] = encKey
|
||||
for index := 1; index < 256; index++ {
|
||||
randCtx64.Seed[index] = 0
|
||||
}
|
||||
|
||||
for index := 0; index < 4; index++ {
|
||||
a, b, c, d, e, f, g, h = mix64(a, b, c, d, e, f, g, h)
|
||||
}
|
||||
|
||||
for index := 0; index < 256; index += 8 {
|
||||
a += randCtx64.Seed[index]
|
||||
b += randCtx64.Seed[index+1]
|
||||
c += randCtx64.Seed[index+2]
|
||||
d += randCtx64.Seed[index+3]
|
||||
e += randCtx64.Seed[index+4]
|
||||
f += randCtx64.Seed[index+5]
|
||||
g += randCtx64.Seed[index+6]
|
||||
h += randCtx64.Seed[index+7]
|
||||
a, b, c, d, e, f, g, h = mix64(a, b, c, d, e, f, g, h)
|
||||
randCtx64.MM[index] = a
|
||||
randCtx64.MM[index+1] = b
|
||||
randCtx64.MM[index+2] = c
|
||||
randCtx64.MM[index+3] = d
|
||||
randCtx64.MM[index+4] = e
|
||||
randCtx64.MM[index+5] = f
|
||||
randCtx64.MM[index+6] = g
|
||||
randCtx64.MM[index+7] = h
|
||||
}
|
||||
|
||||
for index := 0; index < 256; index += 8 {
|
||||
a += randCtx64.MM[index]
|
||||
b += randCtx64.MM[index+1]
|
||||
c += randCtx64.MM[index+2]
|
||||
d += randCtx64.MM[index+3]
|
||||
e += randCtx64.MM[index+4]
|
||||
f += randCtx64.MM[index+5]
|
||||
g += randCtx64.MM[index+6]
|
||||
h += randCtx64.MM[index+7]
|
||||
a, b, c, d, e, f, g, h = mix64(a, b, c, d, e, f, g, h)
|
||||
randCtx64.MM[index] = a
|
||||
randCtx64.MM[index+1] = b
|
||||
randCtx64.MM[index+2] = c
|
||||
randCtx64.MM[index+3] = d
|
||||
randCtx64.MM[index+4] = e
|
||||
randCtx64.MM[index+5] = f
|
||||
randCtx64.MM[index+6] = g
|
||||
randCtx64.MM[index+7] = h
|
||||
}
|
||||
isAAC64(randCtx64)
|
||||
}
|
||||
|
||||
func mix64(a uint64, b uint64, c uint64, d uint64, e uint64, f uint64, g uint64, h uint64) (uint64, uint64, uint64, uint64, uint64, uint64, uint64, uint64) {
|
||||
a -= e
|
||||
f ^= h >> 9
|
||||
h += a
|
||||
b -= f
|
||||
g ^= a << 9
|
||||
a += b
|
||||
c -= g
|
||||
h ^= b >> 23
|
||||
b += c
|
||||
d -= h
|
||||
a ^= c << 15
|
||||
c += d
|
||||
e -= a
|
||||
b ^= d >> 14
|
||||
d += e
|
||||
f -= b
|
||||
c ^= e << 20
|
||||
e += f
|
||||
g -= c
|
||||
d ^= f >> 17
|
||||
f += g
|
||||
h -= d
|
||||
e ^= g << 14
|
||||
g += h
|
||||
return a, b, c, d, e, f, g, h
|
||||
}
|
||||
|
||||
func isAAC64(randCtx64 *RandCtx64) {
|
||||
randCtx64.CC++
|
||||
randCtx64.BB += randCtx64.CC
|
||||
for i, x := range randCtx64.MM {
|
||||
switch i % 4 {
|
||||
case 0:
|
||||
randCtx64.AA = ^(randCtx64.AA ^ randCtx64.AA<<21)
|
||||
case 1:
|
||||
randCtx64.AA = randCtx64.AA ^ randCtx64.AA>>5
|
||||
case 2:
|
||||
randCtx64.AA = randCtx64.AA ^ randCtx64.AA<<12
|
||||
case 3:
|
||||
randCtx64.AA = randCtx64.AA ^ randCtx64.AA>>33
|
||||
}
|
||||
randCtx64.AA += randCtx64.MM[(i+128)%256]
|
||||
y := randCtx64.MM[(x>>3)%256] + randCtx64.AA + randCtx64.BB
|
||||
randCtx64.MM[i] = y
|
||||
randCtx64.BB = randCtx64.MM[(y>>11)%256] + x
|
||||
randCtx64.Seed[i] = randCtx64.BB
|
||||
}
|
||||
}
|
||||
|
||||
// ISAacRandom 随机一个整数
|
||||
func ISAacRandom(randCtx64 *RandCtx64) (r uint64) {
|
||||
r = randCtx64.Seed[randCtx64.RandCnt]
|
||||
if randCtx64.RandCnt == 0 {
|
||||
isAAC64(randCtx64)
|
||||
randCtx64.RandCnt = 255
|
||||
} else {
|
||||
randCtx64.RandCnt--
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package baseutils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PrintLog 打印日志
|
||||
func PrintLog(logStr string) {
|
||||
currentTime := time.Now().Format("2006-01-02 15:04:05")
|
||||
fmt.Println(currentTime + ": " + logStr)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,145 @@
|
||||
package baseutils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ShowObjectValue 打印对象完整信息
|
||||
func ShowObjectValue(object interface{}) {
|
||||
dataType := reflect.TypeOf(object)
|
||||
if dataType.Kind() == reflect.Ptr {
|
||||
dataType = dataType.Elem()
|
||||
}
|
||||
|
||||
ShowStructValue(object, dataType.Name())
|
||||
}
|
||||
|
||||
// ShowStructValue 打印响应信息
|
||||
func ShowStructValue(object interface{}, tag string) {
|
||||
dataValue := reflect.ValueOf(object)
|
||||
dataType := reflect.TypeOf(object)
|
||||
|
||||
if dataType.Kind() == reflect.Ptr {
|
||||
if dataValue.IsNil() {
|
||||
fmt.Println(tag, " = nil")
|
||||
return
|
||||
}
|
||||
|
||||
dataValue = dataValue.Elem()
|
||||
dataType = dataType.Elem()
|
||||
}
|
||||
|
||||
num := dataType.NumField()
|
||||
for i := 0; i < num; i++ {
|
||||
field := dataType.Field(i)
|
||||
fieldName := field.Name
|
||||
fieldValue := dataValue.FieldByName(fieldName)
|
||||
|
||||
if fieldName == "XXX_unrecognized" ||
|
||||
fieldName == "XXX_sizecache" {
|
||||
continue
|
||||
}
|
||||
|
||||
ShowFieldValue(fieldValue, tag+"."+fieldName)
|
||||
}
|
||||
}
|
||||
|
||||
// ShowFieldValue 打印某个属性的值
|
||||
func ShowFieldValue(fieldValue reflect.Value, tag string) {
|
||||
realValue := fieldValue
|
||||
fieldType := fieldValue.Type()
|
||||
|
||||
// 判断是否有效
|
||||
if !fieldValue.IsValid() {
|
||||
fmt.Println(tag, "= nil")
|
||||
return
|
||||
}
|
||||
|
||||
// 如果是指针
|
||||
if fieldType.Kind() == reflect.Ptr {
|
||||
realValue = fieldValue.Elem()
|
||||
fieldType = fieldType.Elem()
|
||||
}
|
||||
|
||||
// 结构数组
|
||||
if fieldType.Kind() == reflect.Slice {
|
||||
for i := 0; i < fieldValue.Len(); i++ {
|
||||
subValue := fieldValue.Index(i)
|
||||
subType := subValue.Type()
|
||||
if subType.Kind() == reflect.Ptr {
|
||||
subType = subType.Elem()
|
||||
subValue = subValue.Elem()
|
||||
}
|
||||
|
||||
if subType.Kind() == reflect.Struct {
|
||||
ShowFieldValue(subValue, tag+"["+strconv.Itoa(i)+"]")
|
||||
} else {
|
||||
fmt.Println(tag+" =", realValue.Interface())
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if fieldValue.Len() == 0 {
|
||||
fmt.Println(tag + " = empty")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 判断是否是结构体
|
||||
if fieldType.Kind() == reflect.Struct {
|
||||
ShowStructValue(fieldValue.Interface(), tag)
|
||||
return
|
||||
}
|
||||
|
||||
// 字符串
|
||||
if fieldType.Kind() == reflect.String {
|
||||
if fieldValue.Kind() == reflect.Ptr {
|
||||
if fieldValue.IsNil() {
|
||||
fmt.Println(tag + " = nil")
|
||||
} else {
|
||||
fmt.Println(tag+" =", realValue.Interface())
|
||||
}
|
||||
} else {
|
||||
if fieldValue.Len() > 0 {
|
||||
fmt.Println(tag+" =", realValue)
|
||||
} else {
|
||||
fmt.Println(tag + " = nil")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !realValue.IsValid() {
|
||||
fmt.Println(tag + " = nil")
|
||||
} else {
|
||||
fmt.Println(tag+" =", realValue)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintBytes PrintBytes
|
||||
func PrintBytes(data []byte, tag string) {
|
||||
fmt.Println("-----------", tag, "------------")
|
||||
length := len(data)
|
||||
for i := 0; i < length; i++ {
|
||||
fmt.Print(data[i], ", ")
|
||||
if i%16 == 0 && i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
|
||||
// PrintBytesHex PrintBytes
|
||||
func PrintBytesHex(data []byte, tag string) {
|
||||
length := len(data)
|
||||
fmt.Println("-----------", tag, "-", length, "------------")
|
||||
for i := 0; i < length; i++ {
|
||||
if i%16 == 0 && i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Printf("0x%02x, ", data[i])
|
||||
}
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
package baseutils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"github.com/gogf/guuid"
|
||||
"image/png"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/boombuler/barcode"
|
||||
"github.com/boombuler/barcode/qr"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
// 转换16进制
|
||||
var numberHexSmall = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
|
||||
var numberHexBig = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}
|
||||
var stringBytes = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
|
||||
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
|
||||
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
|
||||
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-', '+'}
|
||||
var bcd2Bytes = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?'}
|
||||
|
||||
// RandomUUID 随机生成UUID
|
||||
func RandomUUID() string {
|
||||
/*retAdSource := string("")
|
||||
retAdSource = retAdSource + RandomBigHexString(8) + "-"
|
||||
retAdSource = retAdSource + RandomBigHexString(4) + "-"
|
||||
retAdSource = retAdSource + RandomBigHexString(4) + "-"
|
||||
retAdSource = retAdSource + RandomBigHexString(4) + "-"
|
||||
retAdSource = retAdSource + RandomBigHexString(12)*/
|
||||
|
||||
return guuid.New().String()
|
||||
}
|
||||
|
||||
// RandomBSSID 随机生成RandomBSSID
|
||||
func RandomBSSID() string {
|
||||
retAdSource := string("")
|
||||
retAdSource = retAdSource + RandomSmallHexString(2) + "-"
|
||||
retAdSource = retAdSource + RandomSmallHexString(2) + "-"
|
||||
retAdSource = retAdSource + RandomSmallHexString(2) + "-"
|
||||
retAdSource = retAdSource + RandomSmallHexString(2) + "-"
|
||||
retAdSource = retAdSource + RandomSmallHexString(2) + "-"
|
||||
retAdSource = retAdSource + RandomSmallHexString(2)
|
||||
|
||||
return retAdSource
|
||||
}
|
||||
|
||||
func BuildRandomMac() string {
|
||||
// 00:00:00:00:00:00
|
||||
macs := make([]string, 6)
|
||||
for i := range macs {
|
||||
macs[i] = fmt.Sprintf("%02X", rand.Intn(0xff))
|
||||
}
|
||||
|
||||
return strings.Join(macs, ":")
|
||||
}
|
||||
|
||||
// RandomBytes RandomBytes
|
||||
func RandomBytes(length uint32) []byte {
|
||||
retBytes := make([]byte, length)
|
||||
tmpRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
var i uint32
|
||||
for i = 0; i < length; i++ {
|
||||
retBytes[i] = byte(tmpRand.Intn(256))
|
||||
}
|
||||
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// RandomBigHexString RandomBigHexString
|
||||
func RandomBigHexString(length uint32) string {
|
||||
retBytes := make([]byte, length)
|
||||
tmpRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
var i uint32
|
||||
for i = 0; i < length; i++ {
|
||||
tmpIndex := tmpRand.Intn(16)
|
||||
retBytes[i] = numberHexBig[tmpIndex]
|
||||
}
|
||||
|
||||
return string(retBytes)
|
||||
}
|
||||
|
||||
// RandomSmallHexString RandomSmallHexString
|
||||
func RandomSmallHexString(length uint32) string {
|
||||
retBytes := make([]byte, length)
|
||||
tmpRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
var i uint32
|
||||
for i = 0; i < length; i++ {
|
||||
tmpIndex := tmpRand.Intn(16)
|
||||
retBytes[i] = numberHexSmall[tmpIndex]
|
||||
}
|
||||
|
||||
return string(retBytes)
|
||||
}
|
||||
|
||||
// RandomStringByLength 随机固定长度的字符串
|
||||
func RandomStringByLength(length uint32) []byte {
|
||||
retBytes := make([]byte, length)
|
||||
tmpRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
tmpSize := len(stringBytes)
|
||||
var index = uint32(0)
|
||||
for index = 0; index < length; index++ {
|
||||
tmpIndex := tmpRand.Intn(tmpSize)
|
||||
retBytes[index] = stringBytes[tmpIndex]
|
||||
}
|
||||
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// RandomString 随机长度的字符串
|
||||
func RandomString(smallLength uint32, bigLength uint32) []byte {
|
||||
if smallLength >= bigLength || smallLength <= 0 {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
tmpRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
tmpSize := bigLength - smallLength
|
||||
tmpLength := uint32(tmpRand.Intn(int(tmpSize))) + smallLength
|
||||
|
||||
return RandomStringByLength(tmpLength)
|
||||
}
|
||||
|
||||
// BytesToInt32 bytes 转 uint32
|
||||
func BytesToInt32(bytesData []byte) uint32 {
|
||||
length := len(bytesData)
|
||||
if length < 4 {
|
||||
tmpBytes := make([]byte, 4-length)
|
||||
tmpBytes = append(tmpBytes, bytesData[0:]...)
|
||||
return binary.BigEndian.Uint32(tmpBytes)
|
||||
}
|
||||
return binary.BigEndian.Uint32(bytesData)
|
||||
}
|
||||
|
||||
// BytesToInt32SmallEndian 小端整形
|
||||
func BytesToInt32SmallEndian(bytesData []byte) uint32 {
|
||||
return binary.LittleEndian.Uint32(bytesData)
|
||||
}
|
||||
|
||||
// Int32ToBytes uint32 转 bytes
|
||||
func Int32ToBytes(int32Value uint32) []byte {
|
||||
var buf = make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(buf, int32Value)
|
||||
return buf
|
||||
}
|
||||
|
||||
// UInt64ToBytes uint64 转 bytes
|
||||
func UInt64ToBytes(int64Value uint64) []byte {
|
||||
var buf = make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(buf, int64Value)
|
||||
return buf
|
||||
}
|
||||
|
||||
// BigEndianInt32ToLittleEndianInt32 大端整形 转成小端整形
|
||||
func BigEndianInt32ToLittleEndianInt32(intValue uint32) uint32 {
|
||||
tmpBytes := Int32ToBytes(intValue)
|
||||
return binary.LittleEndian.Uint32(tmpBytes)
|
||||
}
|
||||
|
||||
// Int32ToBytesLittleEndian uint32 转 bytes
|
||||
func Int32ToBytesLittleEndian(int32Value uint32) []byte {
|
||||
var buf = make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(buf, int32Value)
|
||||
return buf
|
||||
}
|
||||
|
||||
// Int16ToBytesLittleEndian uint16 转 bytes
|
||||
func Int16ToBytesLittleEndian(int16Value uint16) []byte {
|
||||
var buf = make([]byte, 2)
|
||||
binary.LittleEndian.PutUint16(buf, int16Value)
|
||||
return buf
|
||||
}
|
||||
|
||||
// Int16ToBytesBigEndian uint16 转 bytes
|
||||
func Int16ToBytesBigEndian(int16Value uint16) []byte {
|
||||
var buf = make([]byte, 2)
|
||||
binary.BigEndian.PutUint16(buf, int16Value)
|
||||
return buf
|
||||
}
|
||||
|
||||
// BytesToUint16BigEndian bytes 转 uint16 BigEndian
|
||||
func BytesToUint16BigEndian(bytesData []byte) uint16 {
|
||||
return binary.BigEndian.Uint16(bytesData)
|
||||
}
|
||||
|
||||
// BytesToUint16LittleEndian bytes 转 uint16 LittleEndian
|
||||
func BytesToUint16LittleEndian(bytesData []byte) uint16 {
|
||||
return binary.LittleEndian.Uint16(bytesData)
|
||||
}
|
||||
|
||||
// Int2Byte int 转成 字节数组
|
||||
func Int2Byte(data int) (ret []byte) {
|
||||
var len = unsafe.Sizeof(data)
|
||||
ret = make([]byte, len)
|
||||
var tmp = 0xff
|
||||
var index = uint(0)
|
||||
for index = 0; index < uint(len); index++ {
|
||||
ret[index] = byte((tmp << (index * 8) & data) >> (index * 8))
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// DecodeVByte32 获取变长整形值 和 所占用的字节数
|
||||
// data : 变长整数的字节数组
|
||||
// current : 数组的起始坐标, 从这个坐标开启解析变长整数
|
||||
// return 解密后的整形、占用的字节数
|
||||
func DecodeVByte32(data []byte, current uint32) (uint32, uint32) {
|
||||
var index = uint32(0)
|
||||
for data[current+index] >= 0x80 {
|
||||
index++
|
||||
}
|
||||
|
||||
var retLen = uint32(index + 1)
|
||||
var value = uint32(0)
|
||||
for index != 0 {
|
||||
value <<= 7
|
||||
value |= (uint32)(data[current+index] & 0x7f)
|
||||
index--
|
||||
}
|
||||
|
||||
value <<= 7
|
||||
value |= (uint32)(data[current] & 0x7f)
|
||||
return value, retLen
|
||||
}
|
||||
|
||||
// EncodeVByte32 uint32 转成 变长整形字节数组
|
||||
func EncodeVByte32(num uint32) []byte {
|
||||
retBytes := make([]byte, 0)
|
||||
tmpValue := num
|
||||
for tmpValue >= 0x80 {
|
||||
var tmpByte = byte(0)
|
||||
tmpByte = byte(tmpValue%0x80 + 0x80)
|
||||
tmpValue = tmpValue / 0x80
|
||||
retBytes = append(retBytes, tmpByte)
|
||||
}
|
||||
|
||||
var tmpByte = byte(tmpValue)
|
||||
retBytes = append(retBytes, tmpByte)
|
||||
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// UInt32To16Bytes 整形转换成16进制字节数组
|
||||
func UInt32To16Bytes(intValue uint32) []byte {
|
||||
retBytes := make([]byte, 0)
|
||||
|
||||
tmpValue := intValue
|
||||
for tmpValue > 0 {
|
||||
modValue := tmpValue % 16
|
||||
retBytes = append(retBytes, numberHexSmall[modValue])
|
||||
tmpValue = tmpValue / 16
|
||||
}
|
||||
|
||||
retBytes = reverse(retBytes)
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// 反转字节数组
|
||||
func reverse(data []byte) []byte {
|
||||
retBytes := make([]byte, 0)
|
||||
dataLen := len(data)
|
||||
for dataLen > 0 {
|
||||
retBytes = append(retBytes, data[dataLen-1])
|
||||
dataLen = dataLen - 1
|
||||
}
|
||||
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// HashCode 计算字符串hashcode
|
||||
func HashCode(str string) uint32 {
|
||||
tmpBytes := []byte(str)
|
||||
tmpLen := len(tmpBytes)
|
||||
|
||||
var retHashCode = uint32(0)
|
||||
for index := 0; index < tmpLen; index++ {
|
||||
var tmpValue = uint32(tmpBytes[index])
|
||||
retHashCode = 31*retHashCode + tmpValue
|
||||
}
|
||||
|
||||
return retHashCode
|
||||
}
|
||||
|
||||
// StringCut 截取字符串
|
||||
// srcStr 待截取的字符串
|
||||
// index 截取的开始索引
|
||||
// length 截取的长度
|
||||
func StringCut(srcStr string, index uint32, length uint32) string {
|
||||
srcBytes := []byte(srcStr)
|
||||
tmpBytes := make([]byte, 0)
|
||||
tmpBytes = append(tmpBytes, srcBytes[index:index+length]...)
|
||||
|
||||
retString := string(tmpBytes)
|
||||
return retString
|
||||
}
|
||||
|
||||
// HexStringToBytes 16进制字符串 转bytes
|
||||
func HexStringToBytes(hexString string) []byte {
|
||||
retBytes := make([]byte, 0)
|
||||
count := len(hexString)
|
||||
for index := 0; index < count; index += 2 {
|
||||
tmpStr := StringCut(hexString, uint32(index), 2)
|
||||
value64, _ := strconv.ParseInt(tmpStr, 16, 16)
|
||||
retBytes = append(retBytes, byte(value64))
|
||||
}
|
||||
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// BytesToHexString 字节数组转16进制String
|
||||
func BytesToHexString(data []byte, isBig bool) string {
|
||||
changeBytes := numberHexSmall
|
||||
if isBig {
|
||||
changeBytes = numberHexBig
|
||||
}
|
||||
length := len(data)
|
||||
retBytes := make([]byte, length*2)
|
||||
for index := 0; index < length; index++ {
|
||||
tmpByte := data[index]
|
||||
highIndex := ((tmpByte & 0xf0) >> 4)
|
||||
lowIndex := tmpByte & 0x0f
|
||||
retBytes[index*2] = changeBytes[highIndex]
|
||||
retBytes[index*2+1] = changeBytes[lowIndex]
|
||||
}
|
||||
|
||||
return string(retBytes)
|
||||
}
|
||||
|
||||
// EscapeURL 对Url特殊字符转译
|
||||
func EscapeURL(srcURL string) string {
|
||||
size := len(srcURL)
|
||||
retURL := []byte{}
|
||||
for index := 0; index < size; index++ {
|
||||
// 转译:%
|
||||
if srcURL[index] == '%' {
|
||||
retURL = append(retURL, []byte("%25")[0:]...)
|
||||
continue
|
||||
}
|
||||
// 转译:&
|
||||
if srcURL[index] == '&' {
|
||||
retURL = append(retURL, []byte("%26")[0:]...)
|
||||
continue
|
||||
}
|
||||
// 转译:+
|
||||
if srcURL[index] == '+' {
|
||||
retURL = append(retURL, []byte("%2B")[0:]...)
|
||||
continue
|
||||
}
|
||||
// 转译:/
|
||||
if srcURL[index] == '/' {
|
||||
retURL = append(retURL, []byte("%2F")[0:]...)
|
||||
continue
|
||||
}
|
||||
// 转译:
|
||||
if srcURL[index] == ':' {
|
||||
retURL = append(retURL, []byte("%3A")[0:]...)
|
||||
continue
|
||||
}
|
||||
// 转译:=
|
||||
if srcURL[index] == '=' {
|
||||
retURL = append(retURL, []byte("%3D")[0:]...)
|
||||
continue
|
||||
}
|
||||
// 转译:?
|
||||
if srcURL[index] == '?' {
|
||||
retURL = append(retURL, []byte("%3F")[0:]...)
|
||||
continue
|
||||
}
|
||||
retURL = append(retURL, srcURL[index])
|
||||
}
|
||||
|
||||
return string(retURL)
|
||||
}
|
||||
|
||||
// HongBaoStringToBytes HongBaoStringToBytes
|
||||
func HongBaoStringToBytes(content string) string {
|
||||
retBytes := []byte{}
|
||||
tmpBytes := []byte(content)
|
||||
count := len(tmpBytes)
|
||||
for index := 0; index < count; index++ {
|
||||
byteValue := tmpBytes[index]
|
||||
if byteValue&0x80 != 0 {
|
||||
high4Value := byteValue >> 4
|
||||
low4Value := byteValue & 0xF
|
||||
retBytes = append(retBytes, '%')
|
||||
retBytes = append(retBytes, numberHexBig[high4Value])
|
||||
retBytes = append(retBytes, numberHexBig[low4Value])
|
||||
} else {
|
||||
retBytes = append(retBytes, byteValue)
|
||||
}
|
||||
}
|
||||
|
||||
return string(retBytes)
|
||||
}
|
||||
|
||||
// GetNumberString 获取前面的数字字符串
|
||||
func GetNumberString(srcStr string) string {
|
||||
retBytes := make([]byte, 0)
|
||||
count := len(srcStr)
|
||||
for index := 0; index < count; index++ {
|
||||
if srcStr[index] >= '0' && srcStr[index] <= '9' {
|
||||
retBytes = append(retBytes, srcStr[index])
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return string(retBytes)
|
||||
}
|
||||
|
||||
// BCD2ToASCII BCD2ToASCII
|
||||
func BCD2ToASCII(ascString string) []byte {
|
||||
retBytes := []byte{}
|
||||
size := len(ascString)
|
||||
if size%2 == 1 {
|
||||
size = size + 1
|
||||
ascString = "0" + ascString
|
||||
}
|
||||
tmpAscData := []byte(ascString)
|
||||
for index := 0; index < size; index += 2 {
|
||||
tmpByte := byte(0)
|
||||
for index2 := byte(0); index2 < byte(16); index2++ {
|
||||
if tmpAscData[index] == numberHexBig[index2] {
|
||||
tmpByte = tmpByte + index2<<4
|
||||
}
|
||||
// 判断
|
||||
if tmpAscData[index+1] == numberHexBig[index2] {
|
||||
tmpByte = tmpByte + index2
|
||||
}
|
||||
}
|
||||
retBytes = append(retBytes, tmpByte)
|
||||
}
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// ASCIIToBCD2 ASCIIToBCD2
|
||||
func ASCIIToBCD2(ascData []byte, bFlag bool) []byte {
|
||||
retBytes := []byte{}
|
||||
exchangeBytes := bcd2Bytes
|
||||
if bFlag {
|
||||
exchangeBytes = numberHexBig
|
||||
}
|
||||
|
||||
size := len(ascData)
|
||||
for index := 0; index < size; index++ {
|
||||
high4 := ascData[index] >> 4
|
||||
low4 := ascData[index] & 0xF
|
||||
retBytes = append(retBytes, exchangeBytes[high4])
|
||||
retBytes = append(retBytes, exchangeBytes[low4])
|
||||
}
|
||||
return retBytes
|
||||
}
|
||||
|
||||
// ParseInt 去掉除数字外的其他字符
|
||||
func ParseInt(srcData string) uint32 {
|
||||
retBytes := make([]byte, 0)
|
||||
tmpLen := len(srcData)
|
||||
for index := 0; index < tmpLen; index++ {
|
||||
if srcData[index] >= '0' && srcData[index] <= '9' {
|
||||
retBytes = append(retBytes, srcData[index])
|
||||
}
|
||||
}
|
||||
|
||||
retValue, err := strconv.Atoi(string(retBytes))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return uint32(retValue)
|
||||
}
|
||||
|
||||
// CreateQRCode 生成二维码
|
||||
func CreateQRCode(data string) ([]byte, error) {
|
||||
qrCode, _ := qr.Encode(data, qr.M, qr.Auto)
|
||||
qrCode, _ = barcode.Scale(qrCode, 256, 256)
|
||||
buffer := new(bytes.Buffer)
|
||||
err := png.Encode(buffer, qrCode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buffer.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package baseutils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/flate"
|
||||
"compress/zlib"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/micro/go-micro/util/log"
|
||||
)
|
||||
|
||||
// UnzipByteArray zip解压缩
|
||||
func UnzipByteArray(data []byte) ([]byte, error) {
|
||||
reader, err := zlib.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
retBytes, err := ioutil.ReadAll(reader)
|
||||
defer reader.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return retBytes, nil
|
||||
}
|
||||
|
||||
// CompressByteArray zip压缩
|
||||
func CompressByteArray(data []byte) []byte {
|
||||
var in bytes.Buffer
|
||||
w := zlib.NewWriter(&in)
|
||||
w.Write(data)
|
||||
w.Close()
|
||||
return in.Bytes()
|
||||
}
|
||||
|
||||
// 进行zlib压缩
|
||||
func DoZlibCompress(src []byte) []byte {
|
||||
var in bytes.Buffer
|
||||
w, _ := zlib.NewWriterLevel(&in, zlib.DefaultCompression)
|
||||
w.Write(src)
|
||||
w.Close()
|
||||
return in.Bytes()
|
||||
}
|
||||
|
||||
func AE(msg []byte) []byte {
|
||||
ml := len(msg)
|
||||
var pwd []byte
|
||||
for i := 0; i < ml; i++ {
|
||||
S := 0xAE ^ msg[i]
|
||||
pwd = append(pwd, S)
|
||||
}
|
||||
return DoZlibCompress(pwd)
|
||||
}
|
||||
|
||||
// DeflateZip DeflateZip
|
||||
func DeflateZip(data []byte) []byte {
|
||||
// 一个缓存区压缩的内容
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
|
||||
// 创建一个flate.Writer
|
||||
flateWrite, err := flate.NewWriter(buffer, flate.BestCompression)
|
||||
if err != nil {
|
||||
log.Info("DeflateZip err = ", err)
|
||||
return nil
|
||||
}
|
||||
defer flateWrite.Close()
|
||||
flateWrite.Write(data)
|
||||
flateWrite.Flush()
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
// DeflateUnZip DeflateUnZip
|
||||
func DeflateUnZip(data []byte) []byte {
|
||||
// 一个缓存区压缩的内容
|
||||
flateReader := flate.NewReader(bytes.NewReader(data))
|
||||
defer flateReader.Close()
|
||||
// 输出
|
||||
retBytes, err := ioutil.ReadAll(flateReader)
|
||||
if err != nil {
|
||||
log.Info("DeflateUnZip err = ", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return retBytes
|
||||
}
|
||||
Reference in New Issue
Block a user