pattern/security/e2e-encryption
- Bun
- RabbitMQ
- TypeScript
- amqplib
- node:crypto
- Docker
Cifra o payload na origem com chave que só o destino tem: broker e operador veem bytes opacos. TLS protege o transporte; E2EE protege o conteúdo.
pattern/security/e2e-encryption
Cenário
PIX entre bancos por RabbitMQ compartilhado; uma fila tap só vê ciphertext e o destino lê o PIX.
Planta
Sequência3 passos — reproduza para seguir o fluxo
Como funciona
4passos
Cifra o payload na origem com chave que só o destino tem, opaco para broker e operador
Esconde cada passo: lembre antes de tocar para revelar.
Destino tem par RSA-3072 e publica a chave pública
Origem gera AES-256 e IV de 12 bytes por mensagem e cifra com AES-256-GCM
Chave AES envelopada com RSA-OAEP (SHA-256)
Destino desenvela e decifra; tag, IV ou chave alterados falham no final()
Trade-offs
O que se ganha, o que se paga
Vantagens
Ninguém no broker lê o PIX
Tag GCM rejeita alteração
Custos
Broker não roteia por conteúdo
Chave privada perdida = mensagens irrecuperáveis
Código
pattern/security/e2e-encryption
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq e2e-encryption-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f e2e-encryption-brokerSaída: a fila tap mostra só ciphertext em base64; o destino abre o envelope e imprime o PIX de Maria Silva com amountCents 150000.
Código
src/demo.ts// Demo: a PIX sealed by the origin bank crosses a shared RabbitMQ; the broker tap sees only ciphertext, the destination reads it.
import amqplib from "amqplib";
import { constants, createCipheriv, createDecipheriv, generateKeyPairSync, privateDecrypt, publicEncrypt, randomBytes } from "node:crypto";
type Envelope = { keyAesEncrypted: string; iv: string; tagAuth: string; ciphertext: string };
const EXCHANGE = "pix.e2e";
const OAEP = { padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" };
// The destination bank's RSA pair: only the public key ever leaves it.
const destination = generateKeyPairSync("rsa", { modulusLength: 3072, publicKeyEncoding: { type: "spki", format: "pem" }, privateKeyEncoding: { type: "pkcs8", format: "pem" } });
// Hybrid envelope: a one-time AES-256-GCM key and IV per message, the AES key wrapped with RSA-OAEP.
function envelopeSeal(payload: object, publicKeyPem: string): Envelope {
const keyAes = randomBytes(32);
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", keyAes, iv);
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]);
return { keyAesEncrypted: publicEncrypt({ key: publicKeyPem, ...OAEP }, keyAes).toString("base64"), iv: iv.toString("base64"), tagAuth: cipher.getAuthTag().toString("base64"), ciphertext: ciphertext.toString("base64") };
}
// final() throws on a tag mismatch: an altered byte, IV or key is rejected and the partial plaintext is never used.
function envelopeOpen(envelope: Envelope, privateKeyPem: string): object {
const keyAes = privateDecrypt({ key: privateKeyPem, ...OAEP }, Buffer.from(envelope.keyAesEncrypted, "base64"));
const decipher = createDecipheriv("aes-256-gcm", keyAes, Buffer.from(envelope.iv, "base64"));
decipher.setAuthTag(Buffer.from(envelope.tagAuth, "base64"));
return JSON.parse(Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64")), decipher.final()]).toString("utf8"));
}
// A fanout copies every envelope to the destination's queue and to a tap that stands for anyone with broker access.
const model = await amqplib.connect(Bun.env.E2E_ENCRYPTION_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await model.createConfirmChannel();
await channel.assertExchange(EXCHANGE, "fanout", { durable: false });
const { queue: destinationQueue } = await channel.assertQueue("", { exclusive: true });
const { queue: tapQueue } = await channel.assertQueue("", { exclusive: true });
await Promise.all([destinationQueue, tapQueue].map((queue) => channel.bindQueue(queue, EXCHANGE, "")));
// The origin seals with the destination's public key: the plaintext never leaves it.
const pix = { transactionId: crypto.randomUUID(), payerDocument: "123.456.789-00", payerName: "Maria Silva", receiverKey: "loja@banco.com", amountCents: 150_000 };
channel.publish(EXCHANGE, "", Buffer.from(JSON.stringify(envelopeSeal(pix, destination.publicKey))), { persistent: true });
await channel.waitForConfirms();
for (let attempt = 0; attempt < 50 && (await channel.checkQueue(tapQueue)).messageCount === 0; attempt++) await Bun.sleep(20);
const tapped = await channel.get(tapQueue, { noAck: true });
console.log(` [BROKER TAP] ${tapped ? (JSON.parse(tapped.content.toString()) as Envelope).ciphertext.slice(0, 48) : "-"}…`);
const delivered = await channel.get(destinationQueue, { noAck: true });
console.log(` [DESTINATION] ${delivered ? JSON.stringify(envelopeOpen(JSON.parse(delivered.content.toString()) as Envelope, destination.privateKey)) : "-"}`);
await model.close();
Nível
introdutório
3/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-management-alpine:5672:15672
Variáveis de ambiente
Por que se relacionam
Teste rápido
Qual destes combina com Criptografia Ponta a Ponta?
O servidor não precisa ser confiável. Abrir Zero Trust
Seu progresso
0/157 estudados
Fica salvo só neste navegador.