HTTP 客户端加密 API 参考
crypto 对象提供对 HTTP 客户端加密 API 的访问权限,使您可以使用加密哈希函数、RSA 和 HMAC 生成 HTTP 签名。 然后,您可以在预请求脚本中将这些签名用作变量来签署您的 HTTP 请求。
crypto 接受的方法可以是哈希函数之一(sha1、 sha256、 sha512、 md5)、 HMAC 或 RSA。
哈希方法
方法 | 参数 | 描述 |
|---|
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")) // get variable from http-client.private.env.json
.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"
}
RSA 方法
crypto.subtle 对象使您能够在预请求脚本中使用 RSA 加密。 HTTP 客户端支持 Web Crypto API ,该 API 提供标准的加密功能,例如密钥生成、加密、解密、数字签名、签名验证等。
方法 | 参数 | 描述 |
|---|
encrypt
| algorithm (object):指定加密算法及其参数。 确切的对象结构取决于所使用的算法。
key (object):指定包含加密密钥的 CryptoKey。
data (ArrayBuffer、 TypedArray 或 DataView)
| 使用指定的算法和密钥对提供的数据进行加密。 |
decrypt
| algorithm (object):指定解密算法及其参数。 确切的对象结构取决于所使用的算法。
key (object):指定包含解密密钥的 CryptoKey。
data (ArrayBuffer、 TypedArray 或 DataView)
| 使用指定的算法和密钥对加密数据进行解密。 |
sign
| algorithm (object):指定用于生成数字签名的算法。 确切的对象结构取决于所使用的算法。
key (object):指定包含签名所用密钥的 CryptoKey。 如果 algorithm 表示公开密钥加密系统,则密钥为私钥。
data (ArrayBuffer、 TypedArray 或 DataView)
| 使用指定的算法和密钥生成数字签名。 |
verify
| algorithm (object):指定用于验证签名的算法。 确切的对象结构取决于所使用的算法。
key (object):指定包含验证签名所用密钥的 CryptoKey。 对称算法使用密钥,非对称算法使用公钥。
signature (ArrayBuffer)
data (ArrayBuffer)
| 使用指定的算法和密钥验证数字签名。 |
digest
| algorithm (object 或 string):指定要使用的算法或哈希函数。
data (ArrayBuffer、 TypedArray 或 DataView)
| 使用指定的哈希函数(例如 SHA-256)生成数据的固定长度摘要。 |
generateKey
| algorithm (object):指定用于定义要生成的密钥类型的算法。
extractable (boolean):输入 true 以允许使用 crypto.subtle.exportKey() 或 crypto.subtle.wrapKey() 导出密钥。
keyUsages (字符串数组):指定该密钥允许的操作列表。
| 生成新密钥(用于对称算法)或密钥对(用于非对称算法)。 |
deriveKey
| algorithm (object):指定派生算法及其参数。 确切的对象结构取决于所使用的算法。
baseKey (object):指定用作派生算法输入的 CryptoKey。
derivedKeyAlgorithm (object):指定定义从派生数据中创建何种类型密钥的算法。
extractable (boolean):输入 true 以允许使用 crypto.subtle.exportKey() 或 crypto.subtle.wrapKey() 导出密钥。
keyUsages (字符串数组):指定该密钥允许的操作列表。
| 从基础密钥派生密钥。 |
deriveBits
| algorithm (object):指定派生算法及其参数。 确切的对象结构取决于所使用的算法。
baseKey (object):指定用作派生算法输入的 CryptoKey。
length (number):指定要派生的位数。
| 从基础密钥派生位数组。 |
importKey
| format (string):指定要导入密钥的数据格式。 可能的取值: pkcs8、 spki。
keyData (ArrayBuffer、 TypedArray、 DataView 或 JSONWebKey)
algorithm (object):指定用于定义要导入密钥类型的算法,并提供该算法特定的参数。
extractable (boolean):输入 true 以允许使用 crypto.subtle.exportKey() 或 crypto.subtle.wrapKey() 导出密钥。
keyUsages (字符串数组):指定可使用该密钥执行的操作列表。
| 导入外部可移植格式的密钥并返回一个 CryptoKey 对象。 |
exportKey
| format (字符串):指定导出密钥时使用的数据格式。 可能的值: pkcs8、 spki。
key (对象):指定要导出的 CryptoKey。
| 导出一个 CryptoKey 并返回一个外部可移植格式的密钥。 |
wrapKey
| format (字符串):指定在加密前用于导出密钥的数据格式。 可能的值: pkcs8、 spki。
key (对象):指定要封装的 CryptoKey。
wrappingKey (对象):指定用于加密导出密钥的 CryptoKey。
wrapAlgo (对象):指定用于加密导出密钥的算法。 具体的对象结构取决于所使用的算法。
| 以外部可移植格式导出密钥并对其进行加密。 |
unwrapKey
| format (字符串):指定要解封装的密钥的数据格式。 可能的值: pkcs8、 spki。
wrappedKey (ArrayBuffer)
unwrappingKey (对象):指定用于解密已封装密钥的 CryptoKey。
unwrapAlgo (对象):指定用于解密封装密钥的算法。 具体的对象结构取决于所使用的算法。
unwrapedKeyAlgo (对象):指定定义要解封装的密钥类型的算法,并提供特定算法的参数。
extractable (布尔值):输入 true 以允许使用 crypto.subtle.exportKey() 或 crypto.subtle.wrapKey() 导出密钥。
keyUsages (字符串数组):指定可使用该密钥执行的操作列表。
| 导入并解密已封装的密钥,并返回一个 CryptoKey 对象。 |
示例:
< {%
const keyPair = crypto.subtle.generateKey({
name: "RSA-PSS",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["sign", "verify"])
const text = "Hello, HTTP Client Pre Script!!!";
const data = string2byteArray(text);
const signature = crypto.subtle.sign(
{
name: "RSA-PSS",
},
keyPair.privateKey,
data
);
const verified = crypto.subtle.verify(
{
name: "RSA-PSS",
},
keyPair.publicKey,
signature,
data);
client.log(`${text}, verified: ${verified}`);
%}
GET https://example.com/api/path
示例:生成 JWT
下面是如何创建一个 JSON Web Token (JWT) 的示例,该令牌由三部分组成: base64url 编码的标头、 base64url 编码的有效负载(声明)以及使用 SHA-256 算法生成的加密签名。 然后将此令牌保存为 jwt_token 预请求变量,并可用于对请求进行身份验证。
< {%
const CLIENT_ID = request.environment.get("client_id"); // get variable from http-client.private.env.json
const SECRET = request.environment.get("secret"); // get variable from http-client.private.env.json
function base64UrlEncode(input) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let binary = "";
for (let i = 0; i < input.length; i++) {
binary += input.charCodeAt(i).toString(2).padStart(8, "0");
}
let base64 = "";
for (let i = 0; i < binary.length; i += 6) {
const chunk = binary.substring(i, i + 6);
const index = parseInt(chunk.padEnd(6, "0"), 2);
base64 += chars[index];
}
return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}
const header = {
alg: "HS256",
typ: "JWT"
};
const payload = {
iat: Math.floor(Date.now() / 1000),
client_id: CLIENT_ID,
iss: CLIENT_ID,
user_id: "dev-user",
user_representation: "dev user"
};
const encodedHeader = base64UrlEncode(JSON.stringify(header));
const encodedPayload = base64UrlEncode(JSON.stringify(payload));
const unsignedToken = `${encodedHeader}.${encodedPayload}`;
const signature = crypto.hmac.sha256()
.withTextSecret(SECRET)
.updateWithText(unsignedToken)
.digest().toBase64(true);
const token = `${unsignedToken}.${signature}`;
request.variables.set("jwt_token", token);
%}
GET https://example.com/api/path
Authorization: Bearer {{jwt_token}}
最后修改日期: 2025年 9月 26日