| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- --[[
- * Module: GenerateUserSig (Lua version)
- * Function: Generate UserSig for Tencent Cloud IM/Board SDK
- * Reference: C++ implementation provided
- * Note: This implementation uses Lua's standard libraries and assumes the presence of 'openssl' and 'zlib' Lua modules.
- * Usage: require this module and call gen_user_sig(user_id, sdkappid, secretkey, expiretime)
- --]]
- require("app.app")
- local zlib = require("zlib")
- local base64 = require("app.module.base64")
- local M = {}
- -- Helper: base64 encode, then replace +, /, = as required by Tencent
- local function base64_url_encode(data)
- local b64 = base64.encode(data)
- -- 按照C++代码的字符替换规则
- b64 = b64:gsub("+", "*"):gsub("/", "-"):gsub("=", "_")
- return b64
- end
-
- -- Helper: HMAC-SHA256
- local function hmac_sha256(key, msg)
- -- 确保参数都是字符串类型
- return codec.hmac_sha256(tostring(key), tostring(msg))
- end
- -- Helper: hex string -> binary string
- local function hex_to_bin(hex)
- return (hex:gsub("..", function(cc)
- return string.char(tonumber(cc, 16))
- end))
- end
- -- Helper: Generate the HMAC-SHA256 signature string
- local function gen_hmac_sig(user_id, sdkappid, curr_time, expire_time, secret_key)
- local content = string.format(
- "TLS.identifier:%s\nTLS.sdkappid:%d\nTLS.time:%d\nTLS.expire:%d\n",
- user_id, sdkappid, curr_time, expire_time
- )
- -- 底层返回十六进制摘要,需转为二进制再做标准Base64
- local sig_hex = hmac_sha256(secret_key, content)
- local sig_bin = hex_to_bin(sig_hex)
- return base64.encode(sig_bin)
- end
- -- Main: Generate the UserSig JSON, compress, and base64 encode
- local function gen_user_sig(user_id, sdkappid, secretkey, expiretime)
- assert(user_id and user_id ~= "", "user_id must not be empty")
- assert(tonumber(sdkappid) and tonumber(sdkappid) > 0, "sdkappid must be a positive integer")
- assert(tonumber(expiretime) and tonumber(expiretime) > 0, "expiretime must be a positive integer")
- assert(secretkey and secretkey ~= "", "secretkey must not be empty")
- local curr_time = os.time()
- -- 按官方JS示例:TLS.expire 使用持续时间(秒),不是绝对时间戳
- local expire_time = expiretime
- local sig = gen_hmac_sig(user_id, sdkappid, curr_time, expire_time, secretkey)
- -- Compose JSON string (严格按照C++代码的格式和顺序)
- local json = string.format(
- '{"TLS.ver":"2.0","TLS.identifier":"%s","TLS.sdkappid":%d,"TLS.expire":%d,"TLS.time":%d,"TLS.sig":"%s"}',
- user_id, sdkappid, expire_time, curr_time, sig
- )
- -- Compress with zlib (raw deflate) - 使用Z_BEST_SPEED压缩级别
- local deflater = zlib.deflate()
- local compressed, eof, bytes_in, bytes_out = deflater(json, "finish")
- -- Base64 encode and replace chars as required
- local user_sig = base64_url_encode(compressed)
- return user_sig
- end
- -- Public API
- M.gen_user_sig = gen_user_sig
- return M
|