JavaScript Python PHP
async function executar(values = { "text": "Olá, Bennu!", "direction": "encode", "format": "base64" }) {
const encoder = new TextEncoder();
function toHex(bytes) { return [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join(''); }
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 toBase64Url(bytes) { return toBase64(bytes).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); }
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 option(values, key, options, fallback) {
const value = values[key] ?? fallback;
if (!options.includes(value))
throw new Error(`Opção inválida: ${key}.`);
return value;
}
function encoded(bytes, format) { return format === 'hex' ? toHex(bytes) : format === 'base64' ? toBase64(bytes) : toBase64Url(bytes); }
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.');
{
{
const direction = option(values, 'direction', ['encode', 'decode'], 'encode'), format = option(values, 'format', ['base64', 'base64url'], 'base64');
const input = values.text ?? '';
if (direction === 'encode')
return { text: encoded(encoder.encode(input), format) };
const bytes = format === 'base64url' && input !== '' ? fromBase64Url(input) : fromBase64(input);
return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes) };
}
}
}
return await runSecurityTool("base64", values);
}
import base64
import re
def executar(values=None):
values = {'text': 'Olá, Bennu!', 'direction': 'encode', 'format': 'base64'} 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(text='Olá, Bennu!', direction='encode', format='base64'):
if format not in ('base64', 'base64url') or direction not in ('encode', 'decode'):
raise ValueError('Direção ou formato inválido')
if direction == 'encode':
raw = text.encode('utf-8')
return base64.b64encode(raw).decode('ascii') if format == 'base64' else base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
if format == 'base64url':
if not re.fullmatch('[A-Za-z0-9_-]*', text) or len(text) % 4 == 1:
raise ValueError('Base64 inválido')
return base64.b64decode(text + '=' * (-len(text) % 4), altchars=b'-_', validate=True).decode('utf-8')
if not re.fullmatch('(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?', text):
raise ValueError('Base64 inválido')
return base64.b64decode(text, validate=True).decode('utf-8')
result = process(text=values.get('text', ''), direction=values.get('direction', ''), format=values.get('format', ''))
return {'text':result}
<?php
function executar($values = ['text'=>'Olá, Bennu!','direction'=>'encode','format'=>'base64']) {
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 ($text = 'Olá, Bennu!', $direction = 'encode', $format = 'base64') {
if (!in_array($format,['base64','base64url'],true) || !in_array($direction,['encode','decode'],true)) throw new InvalidArgumentException('Direção ou formato inválido');
if ($direction === 'encode') return $format === 'base64' ? base64_encode($text) : rtrim(strtr(base64_encode($text),'+/','-_'),'=');
$pattern = $format === 'base64url' ? '/^[A-Za-z0-9_-]*$/D' : '~^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$~D';
if (!preg_match($pattern,$text) || ($format === 'base64url' && strlen($text)%4 === 1)) throw new InvalidArgumentException('Base64 inválido');
$raw = base64_decode(strtr($text,'-_','+/'),true);
if ($raw === false || preg_match('//u',$raw) !== 1) throw new InvalidArgumentException('Base64 ou UTF-8 inválido');
return $raw;
};
$result = $process($values['text'] ?? '', $values['direction'] ?? '', $values['format'] ?? '');
return ['text'=>$result];
}