Pular para o conteúdo

Criptografia Ponta a Ponta (E2EE)

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.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

PIX entre bancos por RabbitMQ compartilhado; uma fila tap só vê ciphertext e o destino lê o PIX.

Planta

Sequência
3/3
AES-256-GCM com chave e IV novos,chave AES envelopada com RSA-OAEP do destinoenvelope { keyAesEncrypted, iv, tagAuth, ciphertext }1copia: só bytes opacos2copia3desenvela com a chave privada,confere a tag, lê o PIXBanco de origemRabbitMQ (fanout)Fila tap (operador do broker)Banco de destino
3

3 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.

  1. 1

    Destino tem par RSA-3072 e publica a chave pública

  2. 2

    Origem gera AES-256 e IV de 12 bytes por mensagem e cifra com AES-256-GCM

  3. 3

    Chave AES envelopada com RSA-OAEP (SHA-256)

  4. 4

    Destino desenvela e decifra; tag, IV ou chave alterados falham no final()

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec --user rabbitmq e2e-encryption-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f e2e-encryption-broker

Saída: a fila tap mostra só ciphertext em base64; o destino abre o envelope e imprime o PIX de Maria Silva com amountCents 150000.

Requisitos
BunDocker
Sobe junto
RabbitMQ

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

Linhas de TypeScript
40
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX

Padrões do catálogo que implementa

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-management-alpine:5672:15672

Variáveis de ambiente

E2E_ENCRYPTION_RABBITMQ_URL
amqp://guest:guest@localhost:5672

Por que se relacionam

Teste rápido

Qual destes combina com Criptografia Ponta a Ponta?

Próximo projeto, Segurança & AuditoriaFederated Identity
Esc

↑ ↓ navegarEnter abrir239 resultados