JavaScript Python PHP
async function executar(values = { "token": "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ0ZXN0LXVzZXIifQ." }) {
function toBase64(bytes) {
let binary = '';
for (let i = 0; i < bytes.length; i += 8192)
binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
return btoa(binary);
}
function fromBase64(value) {
const clean = value.replace(/\s/g, '');
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(clean))
throw new Error('Base64 inválido. Confira caracteres e padding (=).');
const bytes = Uint8Array.from(atob(clean), c => c.charCodeAt(0));
if (toBase64(bytes) !== clean)
throw new Error('Base64 não canônico.');
return bytes;
}
function fromBase64Url(value) {
if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1)
throw new Error('Base64URL inválido.');
return fromBase64(value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4));
}
function required(values, key) {
if (!values[key])
throw new Error(`Preencha o campo ${key}.`);
return values[key];
}
function decodeJwt(token) {
const parts = token.trim().split('.');
if (parts.length !== 3)
throw new Error('Informe um JWT JWS com três segmentos. JWE não é suportado.');
const decoder = new TextDecoder('utf-8', { fatal: true });
const header = JSON.parse(decoder.decode(fromBase64Url(parts[0])));
const payload = JSON.parse(decoder.decode(fromBase64Url(parts[1])));
if (!header || typeof header !== 'object' || Array.isArray(header) || !payload || typeof payload !== 'object' || Array.isArray(payload))
throw new Error('Header e payload devem ser objetos JSON.');
if (parts[2])
fromBase64Url(parts[2]);
else if (header.alg !== 'none')
throw new Error('JWT sem assinatura.');
return { header, payload, assinatura: parts[2], assinaturaVerificada: false };
}
async function runSecurityTool(kind, values) {
if (!crypto.subtle)
throw new Error('Esta ferramenta requer Web Crypto em HTTPS ou localhost.');
if (Object.values(values).some(value => value.length > 1000000))
throw new Error('Limite de entrada: 1 milhão de caracteres por campo.');
{
return { text: JSON.stringify(decodeJwt(required(values, 'token')), null, 2), message: 'Conteúdo decodificado. Assinatura e claims não foram validados.' };
}
}
return await runSecurityTool("jwt-decode", values);
}
import base64
import json
import re
def executar(values=None):
values = {'token': 'eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.'} if values is None else values
if not isinstance(values, dict) or any(not isinstance(v,str) or len(v.encode('utf-16-le',errors='surrogatepass')) // 2 > 1000000 for v in values.values()): raise ValueError('Informe campos textuais de até 1 milhão de caracteres')
def integer(key):
raw = values.get(key,'')
if not re.fullmatch(r'[0-9]+',raw): raise ValueError('Informe inteiro válido: ' + key)
return int(raw)
def process(token='eyJhbGciOiJIUzI1NiJ9.eyJub21lIjoiQmVubnUifQ.c2ln'):
parts = token.split('.')
if len(parts) != 3:
raise ValueError('JWT JWS deve ter 3 segmentos')
def decode(part):
return json.loads(base64.b64decode(part + '=' * (-len(part) % 4), altchars=b'-_', validate=True).decode('utf-8'))
return {'header': decode(parts[0]), 'payload': decode(parts[1]), 'assinaturaVerificada': False}
result = process(token=values.get('token', ''))
result['assinatura'] = result.pop('signature',values['token'].split('.')[2])
result['assinaturaVerificada'] = False
return {'text':json.dumps(result,ensure_ascii=False,indent=2), 'message':'Conteúdo decodificado. Assinatura e claims não foram validados.'}
<?php
function executar($values = ['token'=>'eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.']) {
foreach ($values as $value) if (!is_string($value) || strlen($value)>1000000) throw new InvalidArgumentException("Informe campos textuais de até 1 milhão de bytes");
$integer = function ($key) use ($values) { $raw = $values[$key] ?? ""; if (!preg_match("/^[0-9]+$/D",$raw)) throw new InvalidArgumentException("Inteiro inválido: " . $key); return (int)$raw; };
$process = function ($token = 'eyJhbGciOiJIUzI1NiJ9.eyJub21lIjoiQmVubnUifQ.c2ln') {
$parts = explode('.', $token);
if (count($parts) !== 3) throw new InvalidArgumentException('JWT JWS deve ter 3 segmentos');
$decode = function ($part) {
$text = base64_decode(strtr($part, '-_', '+/'), true);
if ($text === false) throw new InvalidArgumentException('Base64 inválido');
return json_decode($text, true, 512, JSON_THROW_ON_ERROR);
};
return ['header' => $decode($parts[0]), 'payload' => $decode($parts[1]), 'assinaturaVerificada' => false];
};
$result = $process($values['token'] ?? '');
$result['assinatura'] = explode('.', $values['token'])[2]; unset($result['signature']); $result['assinaturaVerificada'] = false;
return ['text'=>preg_replace_callback('/^( +)/m',fn($match)=>str_repeat(' ',strlen($match[1])/2),json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)), 'message'=>'Conteúdo decodificado. Assinatura e claims não foram validados.'];
}