1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package auth
- import (
- "bytes"
- "crypto/cipher"
- "crypto/des"
- "crypto/rand"
- "encoding/base64"
- "eta/eta_mini_ht_api/common/exception"
- stringUtils "eta/eta_mini_ht_api/common/utils/string"
- "math/big"
- "regexp"
- )
- const (
- letterBytes = "0123456789"
- )
- func GenerateCode(length int) (string, error) {
- if length <= 0 {
- return "", exception.New(exception.IllegalCodeLength)
- }
- b := make([]byte, length)
- for i := range b {
- n, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes))))
- if err != nil {
- return "", err
- }
- b[i] = letterBytes[n.Int64()]
- }
- return string(b), nil
- }
- func IsValidMobile(mobile string) bool {
- if stringUtils.IsBlank(mobile) {
- return false
- }
- regex := `^(13[0-9]|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$`
- matched, _ := regexp.MatchString(regex, mobile)
- return matched
- }
- func DesBase64Encrypt(origData []byte, desKey string) []byte {
- result, err := tripleDesEncrypt(origData, []byte(desKey))
- if err != nil {
- panic(any(err))
- }
- return []byte(base64.StdEncoding.EncodeToString(result))
- }
- // 3DES加密
- func tripleDesEncrypt(origData, key []byte) ([]byte, error) {
- block, err := des.NewTripleDESCipher(key)
- if err != nil {
- return nil, err
- }
- origData = pKCS5Padding(origData, block.BlockSize())
- // origData = ZeroPadding(origData, block.BlockSize())
- blockMode := cipher.NewCBCEncrypter(block, key[:8])
- crypted := make([]byte, len(origData))
- blockMode.CryptBlocks(crypted, origData)
- return crypted, nil
- }
- func pKCS5Padding(ciphertext []byte, blockSize int) []byte {
- padding := blockSize - len(ciphertext)%blockSize
- padtext := bytes.Repeat([]byte{byte(padding)}, padding)
- return append(ciphertext, padtext...)
- }
|