package utils import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" "github.com/beego/beego/v2/server/web" ) // GetEncryptKey 获取加密密钥 func GetEncryptKey() string { return web.AppConfig.DefaultString("OSS_PARSSE_ENCRYPT_KEY", "jgqwk7sirqlz2602") } // EncryptURL 加密URL func EncryptURL(plainURL string) (string, error) { if plainURL == "" { return "", nil } key := []byte(GetEncryptKey()) plaintext := []byte(plainURL) block, err := aes.NewCipher(key) if err != nil { return "", fmt.Errorf("创建加密器失败: %v", err) } ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", fmt.Errorf("生成IV失败: %v", err) } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) return base64.URLEncoding.EncodeToString(ciphertext), nil } // DecryptURL 解密URL func DecryptURL(encryptedURL string) (string, error) { if encryptedURL == "" { return "", nil } key := []byte(GetEncryptKey()) ciphertext, err := base64.URLEncoding.DecodeString(encryptedURL) if err != nil { return "", fmt.Errorf("Base64解码失败: %v", err) } block, err := aes.NewCipher(key) if err != nil { return "", fmt.Errorf("创建解密器失败: %v", err) } if len(ciphertext) < aes.BlockSize { return "", fmt.Errorf("密文长度不足") } iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) stream.XORKeyStream(ciphertext, ciphertext) return string(ciphertext), nil }