-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecdsa.js
73 lines (61 loc) · 1.91 KB
/
ecdsa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const crypto = require("crypto");
const { readFileSync } = require("fs");
// Load ECDSA private and public keys
const privateKey = readFileSync("private.key", "utf8");
const publicKey = readFileSync("public.key", "utf8");
function encode(email) {
const header = {
alg: "ES256",
typ: "JWT",
};
// Encode header
const encodedHeader = Buffer.from(JSON.stringify(header)).toString(
"base64url",
);
const payload = {
email: email,
exp: Date.now() + 24 * 60 * 60 * 1000,
};
// Encode payload
const encodedPayload = Buffer.from(JSON.stringify(payload)).toString(
"base64url",
);
// Create a signature using ECDSA
const signer = crypto.createSign("sha256")
.update(encodedHeader + "." + encodedPayload);
const signature = signer.sign(privateKey, "base64url");
console.log(encodedHeader + "." + encodedPayload + "." + signature);
return encodedHeader + "." + encodedPayload + "." + signature;
}
function decode(token) {
// Split the token into its components
const parts = token.split(".");
const encodedHeader = parts[0];
const encodedPayload = parts[1];
const signature = parts[2];
// Decode header and payload
const header = JSON.parse(Buffer.from(encodedHeader, "base64url").toString());
const payload = JSON.parse(
Buffer.from(encodedPayload, "base64url").toString(),
);
// Verify signature using ECDSA
const verifier = crypto.createVerify("sha256");
verifier.update(encodedHeader + "." + encodedPayload);
const isVerified = verifier.verify(publicKey, signature, "base64url");
if (payload.exp < Date.now()) {
console.log("JWT Token has expired!");
return false;
} else if (isVerified) {
console.log("JWT Signature is valid.");
console.log("Header:", header);
console.log("Payload:", payload);
return true;
} else {
console.log("JWT Signature is invalid!");
return false;
}
}
module.exports = {
encode,
decode,
};