如何使用Linden Scripting Language(LSL)实现带Timed Hash Verification的Web API调用
如何使用Linden Scripting Language(LSL)实现带Timed Hash Verification的Web API调用
我看你已经用Python搞定了带时间戳哈希验证的API调用,现在帮你把这套逻辑转换成LSL版本——毕竟LSL的函数体系和Python不太一样,得做些适配调整,下面是具体的实现步骤和代码:
核心逻辑拆解
和你Python代码的思路完全一致,LSL版本也需要完成这几个关键步骤:
- 获取当前Unix时间戳
- 把请求数据和时间戳拼接成待哈希的消息
- 用HMAC-SHA256算法生成哈希值
- 带上时间戳和哈希值作为请求头,发送POST请求到目标API
LSL实现代码
因为LSL没有内置的HMAC函数,我们得手动实现HMAC-SHA256的逻辑,再结合LSL的HTTP请求函数完成调用:
// 实现HMAC-SHA256算法(适配LSL字符串处理逻辑) string hmac_sha256(string secret, string message) { integer block_size = 64; // SHA256的标准块大小为64字节 string key = secret; // 如果密钥长度超过块大小,先对密钥做SHA256哈希处理 if (llStringLength(key) > block_size) { key = llSHA256String(key); } // 将密钥填充至块大小长度 while (llStringLength(key) < block_size) { key += "\x00"; } // 生成外部填充和内部填充字符串 string o_key_pad = ""; string i_key_pad = ""; for (integer i = 0; i < block_size; i++) { o_key_pad += llGetSubString(key, i, i) ^ "\x5c"; i_key_pad += llGetSubString(key, i, i) ^ "\x36"; } // 按照HMAC标准流程计算最终哈希值 string inner_hash = llSHA256String(i_key_pad + message); return llSHA256String(o_key_pad + inner_hash); } // 生成带时间戳的哈希值和对应的时间戳字符串 list generate_timed_hash(string secret_key, string data) { integer timestamp = llGetUnixTime(); // 获取当前Unix时间戳 string message = data + (string)timestamp; string hash_value = hmac_sha256(secret_key, message); return [hash_value, (string)timestamp]; } // 存储HTTP请求ID,用于后续匹配响应 integer api_request_id; // 调用目标API的核心函数 testApi() { // 构造请求数据(对应Python中的json.dumps) string data = llJsonSerialize([ "userId", "c088ab7f-dd04-4836-93cd-7ab2843db971" ], 0); string secret_key = "mysecret"; list timed_hash_result = generate_timed_hash(secret_key, data); string hash_value = llList2String(timed_hash_result, 0); string timestamp = llList2String(timed_hash_result, 1); // 设置请求头,包含时间戳和哈希值 list headers = [ "X-Timestamp", timestamp, "X-Hash", hash_value, "Content-Type", "application/x-www-form-urlencoded" ]; // 构造POST表单数据(对应Python中的data={'data': data}) string post_data = "data=" + llEscapeURL(data); // 发送HTTP POST请求 api_request_id = llHTTPRequest("https://some-host/api/secured-plan-detail/", headers, post_data); } // 处理API返回的响应 default { http_response(integer request_id, integer status, list metadata, string body) { if (request_id == api_request_id) { if (status == 200) { llOwnerSay("API响应内容:" + body); } else { llOwnerSay("请求失败,状态码:" + (string)status); } } } state_entry() { testApi(); // 脚本加载完成后自动触发API调用 } }
关键细节说明
- HMAC实现:按照HMAC的标准流程手动实现了密钥填充、内外异或、双重哈希的逻辑,确保和Python中
hmac.new(..., hashlib.sha256)的计算结果完全一致。 - JSON序列化:用LSL内置的
llJsonSerialize替代Python的json.dumps,把LSL列表转换成符合要求的JSON字符串。 - HTTP请求处理:用
llHTTPRequest发送POST请求,通过headers参数传递验证所需的X-Timestamp和X-Hash,POST数据需要用llEscapeURL编码后拼接成表单格式。 - 响应监听:通过
http_response事件监听API的返回结果,将响应内容或错误状态发送给物品所有者查看。
备注:内容来源于stack exchange,提问作者Alok
相关产品推荐
相关产品推荐

