package captcha import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" "time" ) // GenerateEncryptedSceneID 按阿里云文档生成 EncryptedSceneId(仅适用于 V3 架构加密模式)。 // 明文格式: sceneId×tamp&expireTime // 加密: AES-256-CBC + PKCS7Padding,结果为 Base64( IV(16字节) + ciphertext ) func GenerateEncryptedSceneID(sceneId, ekey string, expireSeconds int) (string, error) { if expireSeconds <= 0 || expireSeconds > 86400 { expireSeconds = 3600 } ts := time.Now().Unix() // 秒级时间戳 plaintext := fmt.Sprintf("%s&%d&%d", sceneId, ts, expireSeconds) keyBytes, err := base64.StdEncoding.DecodeString(ekey) if err != nil { return "", fmt.Errorf("decode ekey error: %w", err) } if len(keyBytes) != 32 { return "", fmt.Errorf("invalid ekey length, need 32 bytes after base64 decode, got %d", len(keyBytes)) } block, err := aes.NewCipher(keyBytes) if err != nil { return "", fmt.Errorf("new cipher error: %w", err) } iv := make([]byte, aes.BlockSize) if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", fmt.Errorf("read iv error: %w", err) } padded := pkcs7Pad([]byte(plaintext), aes.BlockSize) ciphertext := make([]byte, len(padded)) mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext, padded) out := append(iv, ciphertext...) return base64.StdEncoding.EncodeToString(out), nil } func pkcs7Pad(src []byte, blockSize int) []byte { padLen := blockSize - len(src)%blockSize if padLen == 0 { padLen = blockSize } pad := bytes.Repeat([]byte{byte(padLen)}, padLen) return append(src, pad...) }