HTTP 客户端 密码学 API 参考
crypto 对象提供对 HTTP 客户端 Crypto API 的访问权限,允许您使用加密哈希函数和 HMAC 生成 HTTP 签名。 然后,您可以在预请求脚本中将这些签名用作变量来签署您的 HTTP 请求。
crypto 接受一种方法,该方法可以是以下哈希函数之一(sha1、 sha256、 sha512、 md5 ),或 hmac。
哈希方法
方法 | 形参 | 描述 |
|---|
updateWithText
| textInput (字符串)
encoding (字符串): textInput 的编码。 默认是 UTF8。
| 将字符串更新为哈希值。 |
updateWithHex
| hexInput (字符串)
| 将十六进制字符串更新为哈希值。 |
updateWithBase64
| base64Input (字符串)
urlSafe (布尔值):如果字符串是使用 Base64 的 URL 安全变体进行编码的,请输入 true。
| 将一个 Base64 字符串更新为哈希。 |
digest().toHex()
| — | 生成哈希并将其转换为十六进制格式。 |
digest().toBase64()
| urlSafe (布尔):如果您想使用 URL 安全的 Base64 变体,请输入 true
| 生成哈希,并将其转换为 Base64 格式。 |
HMAC 方法
crypto.hmac 对象使您能够使用 HMAC 对 HTTP 请求进行签名。 它可以访问所有 hash 方法来生成哈希,并且还有方法可以获取令牌的秘密部分。
方法 | 形参 | 描述 |
|---|
withTextSecret
| textSecret (字符串)
encoding (字符串): textSecret 的编码。 默认是 UTF8。
| 将用于 HMAC 的密钥放入。 |
withHexSecret
| hexSecret (字符串)
| 将密钥置于十六进制格式。 |
withBase64Secret
| base64Input (字符串)
urlSafe (布尔值):如果字符串是使用 Base64 的 URL 安全变体进行编码的,请输入 true。
| 将密钥置于 Base64 格式。 |
示例:
< {%
const signature = crypto.hmac.sha256()
.withTextSecret(request.environment.get("secret"))
.updateWithText(request.body.tryGetSubstituted())
.digest().toHex();
request.variables.set("signature", signature)
const hash = crypto.sha256()
.updateWithText(request.body.tryGetSubstituted())
.digest().toHex();
request.variables.set("hash", hash)
%}
POST https://httpbin.org/post
X-My-Signature: {{signature}}
X-My-Hash: {{hash}}
Content-Type: application/json
{
"prop": "value"
}
最后修改日期: 2025年 4月 24日