package utils import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "errors" "fmt" "io" ) // 将整数转换为固定长度的字符串 func intToFixedLengthString(num int, length int) string { return fmt.Sprintf("%0*d", length, num) } // 加密函数 func IDEncrypt(plainText, key string) (string, error) { block, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } plainTextBytes := []byte(plainText) cipherText := make([]byte, aes.BlockSize+len(plainTextBytes)) iv := cipherText[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", err } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(cipherText[aes.BlockSize:], plainTextBytes) // 使用URL安全的Base64编码 encrypted := base64.URLEncoding.EncodeToString(cipherText) return encrypted, nil } // 解密函数 func IDDecrypt(encryptedText, key string) (string, error) { cipherText, err := base64.URLEncoding.DecodeString(encryptedText) if err != nil { return "", err } block, err := aes.NewCipher([]byte(key)) if err != nil { return "", err } if len(cipherText) < aes.BlockSize { return "", errors.New("cipherText too short") } iv := cipherText[:aes.BlockSize] cipherText = cipherText[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) stream.XORKeyStream(cipherText, cipherText) return string(cipherText), nil }