gpt4 book ai didi

javascript - JWT 与 k6 签约

转载 作者:行者123 更新时间:2023-12-01 02:54:46 28 4
gpt4 key购买 nike

如何使用 JWT 对 JSON 对象进行编码签名为k6

export default function() {

const mySecret = "aaaaaaa";
const token = jwt.encode({ foo: 'bar' }, mySecret);

}

最佳答案

您可以使用内置 k6/encodingk6/crypto与 JWT 一起使用的模块。

由于 k6/crypto 模块尚不支持公钥加密,因此您只能使用共享 key 来签署 JWT(无需在纯 JS 中进行加密)。

这是一个示例脚本:

import crypto from "k6/crypto";
import encoding from "k6/encoding";

const algToHash = {
HS256: "sha256",
HS384: "sha384",
HS512: "sha512"
};

function sign(data, hashAlg, secret) {
let hasher = crypto.createHMAC(hashAlg, secret);
hasher.update(data);

// Some manual base64 rawurl encoding as `Hasher.digest(encodingType)`
// doesn't support that encoding type yet.
return hasher.digest("base64").replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
}

function encode(payload, secret, algorithm) {
algorithm = algorithm || "HS256";
let header = encoding.b64encode(JSON.stringify({ typ: "JWT", alg: algorithm }), "rawurl");
payload = encoding.b64encode(JSON.stringify(payload), "rawurl");
let sig = sign(header + "." + payload, algToHash[algorithm], secret);
return [header, payload, sig].join(".");
}

function decode(token, secret, algorithm) {
let parts = token.split('.');
let header = JSON.parse(encoding.b64decode(parts[0], "rawurl"));
let payload = JSON.parse(encoding.b64decode(parts[1], "rawurl"));
algorithm = algorithm || algToHash[header.alg];
if (sign(parts[0] + "." + parts[1], algorithm, secret) != parts[2]) {
throw Error("JWT signature verification failed");
}
return payload;
}

export default function() {
let message = { key2: "value2" };
let token = encode(message, "secret");
console.log("encoded", token);
let payload = decode(token, "secret");
console.log("decoded", JSON.stringify(payload));
}

关于javascript - JWT 与 k6 签约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46767543/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com