feat(new tool): JWT Generator + JWT Signature verification

Fix #1309
This commit is contained in:
sharevb authored and ShareVB committed 2025-01-26 22:00:56 +01:00
1 parent a8a2a0d3f0
commit 47917dcc76
10 files changed
+307 -9

No files matched your search

+2
View File
@@ -244,6 +244,7 @@ declare module '@vue/runtime-core' {
'NanoMemo.content': typeof import('./src/tools/nano-memo/nano-memo.content.md')['default']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NCode: typeof import('naive-ui')['NCode']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
@@ -253,6 +254,7 @@ declare module '@vue/runtime-core' {
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
+1
View File
@@ -129,6 +129,7 @@
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"jose": "^5.9.6",
"ical-generator": "^8.0.1",
"ical.js": "^2.1.0",
"iconv-lite": "^0.6.3",
+8 -1
View File
@@ -329,6 +329,9 @@ dependencies:
jks-js:
specifier: ^1.1.4
version: 1.1.4
jose:
specifier: ^5.9.6
version: 5.9.6
jpeg-quality-estimator:
specifier: ^1.0.1
version: 1.0.1
@@ -6988,7 +6991,7 @@ packages:
/@vueuse/shared@10.0.0(vue@3.3.4):
resolution: {integrity: sha512-Zh3LgJqvUBWVY3SiMvXanTcfAneGbt63QPczBRDNgQ6jd/ehodO9a1lCFzaA6SWJJoI+ugVTjHFYJdoR656DVQ==}
dependencies:
vue-demi: 0.14.5(vue@3.3.4)
vue-demi: 0.14.10(vue@3.3.4)
transitivePeerDependencies:
- '@vue/composition-api'
- vue
@@ -11797,6 +11800,10 @@ packages:
engines: {node: '>= 0.6.0'}
dev: false
/jose@5.9.6:
resolution: {integrity: sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ==}
dev: false
/jpeg-js@0.4.4:
resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==}
+2
View File
@@ -25,6 +25,7 @@ import { tool as angleConverter } from './angle-converter';
import { tool as floatingPointNumberConverter } from './floating-point-number-converter';
import { tool as snowflakeIdExtractor } from './snowflake-id-extractor';
import { tool as emailNormalizer } from './email-normalizer';
import { tool as jwtGenerator } from './jwt-generator';
import { tool as gptTokenEstimator } from './gpt-token-estimator';
import { tool as myIp } from './my-ip';
import { tool as geoDistanceCalculator } from './geo-distance-calculator';
@@ -361,6 +362,7 @@ export const toolsByCategory: ToolCategory[] = [
otpCodeGeneratorAndValidator,
mimeTypes,
jwtParser,
jwtGenerator,
keycodeInfo,
slugifyString,
htmlWysiwygEditor,
+29
View File
@@ -0,0 +1,29 @@
import { Key } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'JWT Generator',
path: '/jwt-generator',
description: 'JWT Token generator and editor',
keywords: [
'jwt',
'generator',
'editor',
'encode',
'typ',
'alg',
'iss',
'sub',
'aud',
'exp',
'nbf',
'iat',
'jti',
'json',
'web',
'token',
],
component: () => import('./jwt-generator.vue'),
icon: Key,
createdAt: new Date('2024-08-15'),
});
@@ -0,0 +1,15 @@
export const jwsAlgorithms = [
{ alg: 'HS256', keyDesc: '256 bit (32 byte) secret', key: 'secret', verify: 'HMAC-SHA256' },
{ alg: 'HS384', keyDesc: '384 bit (48 byte) secret', key: 'secret', verify: 'HMAC-SHA384' },
{ alg: 'HS512', keyDesc: '512 bit (64 byte) secret', key: 'secret', verify: 'HMAC-SHA512' },
{ alg: 'ES256', keyDesc: 'NIST P-256 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA256' },
{ alg: 'ES256K', keyDesc: 'secp256k1 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA256(secp256k1)' },
{ alg: 'ES384', keyDesc: 'NIST P-384 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA384' },
{ alg: 'ES512', keyDesc: 'NIST P-521 elliptic curve key', key: 'keyspair', verify: 'ECDSA-SHA512' },
{ alg: 'PS256', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-PSS-SHA256' },
{ alg: 'PS384', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-PSS-SHA384' },
{ alg: 'PS512', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-PSS-SHA512' },
{ alg: 'RS256', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-SHA256' },
{ alg: 'RS384', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-SHA384' },
{ alg: 'RS512', keyDesc: 'RSA key of at least 2048 bit modulus length', key: 'keyspair', verify: 'RSA-SHA512' },
];
+187
View File
@@ -0,0 +1,187 @@
<script setup lang="ts">
import * as jose from 'jose';
import { type KeyLike } from 'jose';
import JSON5 from 'json5';
import { jwsAlgorithms } from './jwt-generator.constants';
import { useValidation } from '@/composable/validation';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const payload = ref(`{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}`);
const alg = useQueryParamOrStorage({ name: 'alg', storageName: 'jwt-gen:alg', defaultValue: 'HS512' });
const algInfo = computed(() => jwsAlgorithms.find(a => a.alg === alg.value) || { alg: 'UNK', keyDesc: '', key: 'secret', verify: '' });
const isSecret = computed(() => algInfo.value.key === 'secret');
const secret = ref('');
const publicKeyPEM = ref('');
const publicKeyJWK = ref('');
const privateKeyJWK = ref('');
const privateKeyPEM = ref('');
watch(publicKeyPEM, async (newValue) => {
try {
publicKeyJWK.value = JSON.stringify(await jose.exportJWK(await jose.importSPKI(newValue, alg.value, { extractable: true })), null, 2);
}
catch {
}
}, { immediate: true });
watch(privateKeyPEM, async (newValue) => {
try {
privateKeyJWK.value = JSON.stringify(await jose.exportJWK(await jose.importPKCS8(newValue, alg.value, { extractable: true })), null, 2);
}
catch {
}
}, { immediate: true });
watch(publicKeyJWK, async (newValue) => {
try {
publicKeyPEM.value = await jose.exportSPKI(await jose.importJWK({ ...JSON.parse(newValue), ...{ ext: true } }, alg.value) as KeyLike);
}
catch {
}
}, { immediate: true });
watch(privateKeyJWK, async (newValue) => {
try {
privateKeyPEM.value = await jose.exportPKCS8(await jose.importJWK({ ...JSON.parse(newValue), ...{ ext: true } }, alg.value) as KeyLike);
}
catch {
}
}, { immediate: true });
watchEffect(async () => {
if (isSecret.value) {
secret.value = 'your-secret';
privateKeyJWK.value = '';
publicKeyJWK.value = '';
privateKeyPEM.value = '';
publicKeyPEM.value = '';
}
else {
const { publicKey, privateKey } = await jose.generateKeyPair(alg.value, { extractable: true });
privateKeyJWK.value = JSON.stringify(await jose.exportJWK(privateKey), null, 2);
publicKeyJWK.value = JSON.stringify(await jose.exportJWK(publicKey), null, 2);
privateKeyPEM.value = await jose.exportPKCS8(privateKey);
publicKeyPEM.value = await jose.exportSPKI(publicKey);
}
});
const header = computed(() => JSON.stringify({ alg: alg.value, typ: 'JWT' }, null, 2));
const encodedJWT = computedAsync(async () => {
const isSecretValue = isSecret.value;
const secretValue = secret.value;
const privateKeyValue = privateKeyJWK.value;
const algValue = alg.value;
const payloadValue = payload.value;
try {
let privateKeyOrSecret;
if (isSecretValue) {
privateKeyOrSecret = new TextEncoder().encode(secretValue);
}
else {
privateKeyOrSecret = await jose.importJWK(JSON.parse(privateKeyValue), algValue);
}
return {
token: await (new jose.SignJWT(JSON5.parse(payloadValue))
.setProtectedHeader({ alg: algValue })
.sign(privateKeyOrSecret)),
error: '',
};
}
catch (e: any) {
return { error: e.toString(), token: '' };
}
});
const jsonInputValidation = useValidation({
source: payload,
rules: [
{
message: 'Invalid JSON string',
validator: value => JSON5.parse(value),
},
],
});
</script>
<template>
<div>
<c-select
v-model:value="alg"
:options="jwsAlgorithms.map(a => ({ value: a.alg, label: `${a.alg}: ${a.verify}` }))"
placeholder="Algorithms"
mb-2
/>
<n-form-item label="Description:" label-placement="left" mb-2>
{{ algInfo.alg }}: {{ algInfo.keyDesc }} (verify with {{ algInfo.verify }})
</n-form-item>
<c-card title="Token Content" mb-2>
<n-form-item label="Header:">
<textarea-copyable :value="header" language="json" />
</n-form-item>
<c-input-text
v-model:value="payload"
label="Payload:"
multiline
rows="5"
autosize
placeholder="JSON payload"
:validation="jsonInputValidation"
/>
</c-card>
<c-card :title="isSecret ? 'Token Secret' : 'Token Keys'" mb-2>
<c-input-text v-if="isSecret" v-model:value="secret" />
<div v-if="!isSecret">
<n-form-item label="Public Key (PEM):">
<c-input-text
v-model:value="publicKeyPEM"
multiline
rows="5"
autosize
/>
</n-form-item>
<n-form-item label="Private Key (PEM):">
<c-input-text
v-model:value="privateKeyPEM"
multiline
rows="5"
autosize
/>
</n-form-item>
<n-divider />
<n-form-item label="Public Key (JWK):">
<c-input-text
v-model:value="publicKeyJWK"
multiline
rows="5"
autosize
/>
</n-form-item>
<n-form-item label="Private Key (JWK):">
<c-input-text
v-model:value="privateKeyJWK"
multiline
rows="5"
autosize
/>
</n-form-item>
</div>
</c-card>
<c-card v-if="encodedJWT" title="Generated JWT Token:" mb-2>
<textarea-copyable v-if="encodedJWT.token" :value="encodedJWT.token" word-wrap />
<c-alert v-if="encodedJWT.error">
{{ encodedJWT.error }}
</c-alert>
</c-card>
</div>
</template>
+2 -3
View File
@@ -1,11 +1,10 @@
import { Key } from '@vicons/tabler';
import { defineTool } from '../tool';
import { translate } from '@/plugins/i18n.plugin';
export const tool = defineTool({
name: translate('tools.jwt-parser.title'),
name: 'JWT parser',
path: '/jwt-parser',
description: translate('tools.jwt-parser.description'),
description: 'Parse and decode your JSON Web Token (jwt) and display its content.',
keywords: [
'jwt',
'parser',
+6 -2
View File
@@ -2,7 +2,11 @@ import jwtDecode, { type JwtHeader, type JwtPayload } from 'jwt-decode';
import _ from 'lodash';
import { ALGORITHM_DESCRIPTIONS, CLAIM_DESCRIPTIONS } from './jwt-parser.constants';
export { decodeJwt };
export { decodeJwt, getJwtAlgorithm };
function getJwtAlgorithm({ jwt }: { jwt: string }) {
return jwtDecode<JwtHeader>(jwt, { header: true }).alg;
}
function decodeJwt({ jwt }: { jwt: string }) {
const rawHeader = jwtDecode<JwtHeader>(jwt, { header: true });
@@ -19,7 +23,7 @@ function decodeJwt({ jwt }: { jwt: string }) {
function parseClaims({ claim, value }: { claim: string; value: unknown }) {
const claimDescription = CLAIM_DESCRIPTIONS[claim];
const formattedValue = _.isPlainObject(value) || _.isArray(value) ? JSON.stringify(value, null, 3) : _.toString(value);
const formattedValue = _.isPlainObject(value) ? JSON.stringify(value, null, 3) : _.toString(value);
const friendlyValue = getFriendlyValue({ claim, value });
return {
+55 -3
View File
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { decodeJwt } from './jwt-parser.service';
import * as jose from 'jose';
import JSON5 from 'json5';
import { decodeJwt, getJwtAlgorithm } from './jwt-parser.service';
import { useValidation } from '@/composable/validation';
import { isNotThrowing } from '@/utils/boolean';
import { withDefaultOnError } from '@/utils/defaults';
@@ -26,6 +28,41 @@ const validation = useValidation({
},
],
});
const secretOrPublicKey = ref('');
const signatureVerification = computedAsync(async () => {
const secretOrPublicKeyValue = secretOrPublicKey.value?.trim();
if (!secretOrPublicKeyValue) {
return { error: 'No secret or key provided' };
}
const jwt = rawJwt.value?.trim();
if (!jwt) {
return { error: 'No JWT token provided' };
}
try {
const alg = getJwtAlgorithm({ jwt }) || 'unk';
if (secretOrPublicKeyValue.startsWith('{')) {
const jwk = JSON5.parse(secretOrPublicKeyValue);
const publicKey = await jose.importJWK(jwk, alg);
await jose.jwtVerify(jwt, publicKey);
}
else if (secretOrPublicKeyValue.includes('-----BEGIN PUBLIC KEY-----')) {
const publicKey = await jose.importSPKI(secretOrPublicKeyValue, alg);
await jose.jwtVerify(jwt, publicKey);
}
else {
const secret = new TextEncoder().encode(secretOrPublicKeyValue);
await jose.jwtVerify(jwt, secret);
}
return { error: '' };
}
catch (e: any) {
return { error: `Key or secret or verification error: ${e.toString()}` };
}
});
</script>
<template>
@@ -39,7 +76,7 @@ const validation = useValidation({
{{ section.title }}
</th>
<tr v-for="{ claim, claimDescription, friendlyValue, value } in decodedJWT[section.key]" :key="claim + value">
<td class="claims" style="vertical-align: top;">
<td class="claims">
<span font-bold>
{{ claim }}
</span>
@@ -47,7 +84,7 @@ const validation = useValidation({
({{ claimDescription }})
</span>
</td>
<td style="word-wrap: break-word;word-break: break-all;">
<td>
<span>{{ value }}</span>
<span v-if="friendlyValue" ml-2 op-70>
({{ friendlyValue }})
@@ -57,6 +94,21 @@ const validation = useValidation({
</template>
</tbody>
</n-table>
<c-card title="Signature Validation">
<c-input-text
v-model:value="secretOrPublicKey" label="Secret or Public Key (SPKI or JWK)"
placeholder="Put your secret or Public key here..." rows="5" multiline raw-text autofocus mb-3
/>
<c-alert v-if="signatureVerification?.error">
{{ signatureVerification.error }}
</c-alert>
<n-alert v-if="!signatureVerification?.error" type="success">
Signature verified
</n-alert>
</c-card>
</c-card>
</template>