Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { createHmac } from "crypto";
const createHash = (secret: string, payload: string): string =>
createHmac("sha256", secret).update(payload).digest("base64");
export const generateToken = (secret: string, payload: string): string => {
return createHash(secret, payload) + "$" + payload;
};
export const verifyToken = (secret: string, token: string): string | undefined => {
const splitToken = token.split("$", 2);
if (splitToken.length !== 2) {
return;
}
const [hash, payload] = splitToken;
if (createHash(secret, payload) !== hash) {
return;
}
return payload;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment