JavaScript Python PHP
async function executar(values) {
const variant = values.variant ?? "aes";
async function convertSelected() {
if (variant === "aes") {
const parameters = { ...{"bits":"256","format":"base64"}, ...values, ...{} };
async function convert(values = { "bits": "256", "format": "base64" }) {
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 toBase64Url(bytes) { return toBase64(bytes).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); }
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 bits = Number(option(values, 'bits', ['128', '192', '256'], '256'));
const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: bits }, true, ['encrypt', 'decrypt']);
return { text: encoded(new Uint8Array(await crypto.subtle.exportKey('raw', key)), option(values, 'format', ['hex', 'base64', 'base64url'], 'base64')) };
}
}
}
return await runSecurityTool("aes", values);
}
return await convert(parameters);
}
if (variant === "rsa") {
const parameters = { ...{"bits":"2048","usage":"RSA-OAEP"}, ...values, ...{} };
async function convert(values = { "bits": "2048", "usage": "RSA-OAEP" }) {
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 pem(bytes, label) { return `-----BEGIN ${label}-----\n${toBase64(bytes).match(/.{1,64}/g).join('\n')}\n-----END ${label}-----\n`; }
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;
}
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 name = option(values, 'usage', ['RSA-OAEP', 'RSA-PSS', 'RSASSA-PKCS1-v1_5'], 'RSA-OAEP');
const bits = Number(option(values, 'bits', ['2048', '3072', '4096'], '2048'));
const keys = await crypto.subtle.generateKey({ name, modulusLength: bits, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, name === 'RSA-OAEP' ? ['encrypt', 'decrypt'] : ['sign', 'verify']);
const publicKey = pem(new Uint8Array(await crypto.subtle.exportKey('spki', keys.publicKey)), 'PUBLIC KEY');
const privateKey = pem(new Uint8Array(await crypto.subtle.exportKey('pkcs8', keys.privateKey)), 'PRIVATE KEY');
return { text: publicKey + '\n' + privateKey, files: [{ name: 'public-key.pem', content: publicKey }, { name: 'private-key.pem', content: privateKey }] };
}
}
}
return await runSecurityTool("rsa", values);
}
return await convert(parameters);
}
throw new Error("Selecione uma modalidade válida de segurança.");
}
return await convertSelected();
}
import secrets
import base64
import re
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization as s
def executar(values):
variant = values.get("variant", "aes")
if variant == "aes":
parameters = {**{"bits":"256","format":"base64"}, **values, **{}}
def convert(values=None):
values = {'bits': '256', '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(bits=256, format='base64'):
if type(bits) is not int or bits not in (128, 192, 256):
raise ValueError('Tamanho AES inválido')
def encode(raw):
if format == 'hex':
return raw.hex()
if format == 'base64':
return base64.b64encode(raw).decode('ascii')
if format == 'base64url':
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
raise ValueError('Formato inválido')
return encode(secrets.token_bytes(bits // 8))
result = process(bits=integer('bits'), format=values.get('format', ''))
return {'text':result}
return convert(parameters)
if variant == "rsa":
parameters = {**{"bits":"2048","usage":"RSA-OAEP"}, **values, **{}}
def convert(values=None):
values = {'bits': '2048', 'usage': 'RSA-OAEP'} 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(bits=2048):
if type(bits) is not int or bits not in (2048, 3072, 4096):
raise ValueError('Tamanho RSA inválido')
results = []
key = rsa.generate_private_key(public_exponent=65537, key_size=bits)
results.append(key.public_key().public_bytes(s.Encoding.PEM, s.PublicFormat.SubjectPublicKeyInfo).decode())
results.append(key.private_bytes(s.Encoding.PEM, s.PrivateFormat.PKCS8, s.NoEncryption()).decode())
return results[0] if len(results) == 1 else results
if values.get('usage') not in ('RSA-OAEP','RSA-PSS','RSASSA-PKCS1-v1_5'): raise ValueError('Finalidade RSA inválida')
result = process(bits=integer('bits'))
return {'text':result[0]+'\n'+result[1], 'files':[{'name':'public-key.pem','content':result[0]},{'name':'private-key.pem','content':result[1]}]}
return convert(parameters)
raise ValueError("Selecione uma modalidade válida de segurança.")
<?php
function executar($values) {
$variant = $values["variant"] ?? "aes";
$convertSelected = function () use ($variant, $values) {
if ($variant === "aes") {
$parameters = array_replace(["bits" => "256", "format" => "base64"], $values, []);
$convert = function ($values = ['bits'=>'256','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 ($bits = 256, $format = 'base64') {
if (!in_array($bits,[128,192,256],true)) throw new InvalidArgumentException('Tamanho AES inválido');
$encode = function ($raw) use ($format) {
return match ($format) {
'hex' => bin2hex($raw),
'base64' => base64_encode($raw),
'base64url' => rtrim(strtr(base64_encode($raw), '+/', '-_'), '='),
default => throw new InvalidArgumentException('Formato inválido'),
};
};
return $encode(random_bytes(intdiv($bits,8)));
};
$result = $process($integer('bits'), $values['format'] ?? '');
return ['text'=>$result];
};
return $convert($parameters);
}
if ($variant === "rsa") {
$parameters = array_replace(["bits" => "2048", "usage" => "RSA-OAEP"], $values, []);
$convert = function ($values = ['bits'=>'2048','usage'=>'RSA-OAEP']) {
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 ($bits = 2048) {
if (!in_array($bits,[2048,3072,4096],true)) throw new InvalidArgumentException('Tamanho RSA inválido');
$results = [];
$key = openssl_pkey_new(['private_key_bits' => $bits, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
if ($key === false) throw new RuntimeException('Falha ao gerar RSA');
if (!openssl_pkey_export($key, $private)) throw new RuntimeException('Falha ao exportar');
$details = openssl_pkey_get_details($key);
if ($details === false) throw new RuntimeException('Falha ao exportar a chave pública');
$results[] = $details['key'];
$results[] = $private;
// O par RSA pode ser importado com a finalidade e o padding apropriados.
return count($results) === 1 ? $results[0] : $results;
};
if (!in_array($values['usage'] ?? '', ['RSA-OAEP','RSA-PSS','RSASSA-PKCS1-v1_5'],true)) throw new InvalidArgumentException('Finalidade RSA inválida');
$result = $process($integer('bits'));
return ['text'=>$result[0] . "\n" . $result[1], 'files'=>[['name'=>'public-key.pem','content'=>$result[0]],['name'=>'private-key.pem','content'=>$result[1]]]];
};
return $convert($parameters);
}
throw new InvalidArgumentException("Selecione uma modalidade válida de segurança.");
};
return $convertSelected();
}