crypto.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package utils
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "encoding/base64"
  7. "fmt"
  8. "io"
  9. "github.com/beego/beego/v2/server/web"
  10. )
  11. // GetEncryptKey 获取加密密钥
  12. func GetEncryptKey() string {
  13. return web.AppConfig.DefaultString("OSS_PARSSE_ENCRYPT_KEY", "jgqwk7sirqlz2602")
  14. }
  15. // EncryptURL 加密URL
  16. func EncryptURL(plainURL string) (string, error) {
  17. if plainURL == "" {
  18. return "", nil
  19. }
  20. key := []byte(GetEncryptKey())
  21. plaintext := []byte(plainURL)
  22. block, err := aes.NewCipher(key)
  23. if err != nil {
  24. return "", fmt.Errorf("创建加密器失败: %v", err)
  25. }
  26. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  27. iv := ciphertext[:aes.BlockSize]
  28. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  29. return "", fmt.Errorf("生成IV失败: %v", err)
  30. }
  31. stream := cipher.NewCFBEncrypter(block, iv)
  32. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  33. return base64.URLEncoding.EncodeToString(ciphertext), nil
  34. }
  35. // DecryptURL 解密URL
  36. func DecryptURL(encryptedURL string) (string, error) {
  37. if encryptedURL == "" {
  38. return "", nil
  39. }
  40. key := []byte(GetEncryptKey())
  41. ciphertext, err := base64.URLEncoding.DecodeString(encryptedURL)
  42. if err != nil {
  43. return "", fmt.Errorf("Base64解码失败: %v", err)
  44. }
  45. block, err := aes.NewCipher(key)
  46. if err != nil {
  47. return "", fmt.Errorf("创建解密器失败: %v", err)
  48. }
  49. if len(ciphertext) < aes.BlockSize {
  50. return "", fmt.Errorf("密文长度不足")
  51. }
  52. iv := ciphertext[:aes.BlockSize]
  53. ciphertext = ciphertext[aes.BlockSize:]
  54. stream := cipher.NewCFBDecrypter(block, iv)
  55. stream.XORKeyStream(ciphertext, ciphertext)
  56. return string(ciphertext), nil
  57. }