Study guide
Cryptography and keys: public, private, sessions and SSH.
How encryption, signatures and key pairs work, how apps keep a private key on the device, how the session carries on from there, and what SSH does step by step.
Resumo (TL;DR)Summary (TL;DR)
- Chave simétrica: um segredo só, igual nos dois lados (rápido, mas difícil de combinar). Par de chaves: uma pública (todos podem ter) e uma privada (só você). O que uma fecha, só a outra abre.Symmetric key: a single secret, the same on both sides (fast, but hard to agree on). Key pair: a public key (everyone may have it) and a private key (only you). What one locks, only the other unlocks.
- Com o par você cifra (pública cifra, privada decifra) e assina (privada assina, pública verifica). Na prática, tudo combina os dois mundos: o par acorda uma chave simétrica e a simétrica protege os dados (TLS, SSH).With the pair you encrypt (public encrypts, private decrypts) and sign (private signs, public verifies). In practice everything mixes both worlds: the pair agrees on a symmetric key and the symmetric key protects the data (TLS, SSH).
- Apps com a chave privada no aparelho (passkeys, bancos, autenticadores) provam quem você é assinando um desafio; o servidor só guarda a pública. Depois da prova, uma sessão (cookie ou token) evita repetir a assinatura a cada requisição. O SSH usa o mesmo truque: o servidor se prova a você, depois você se prova a ele.Apps with the private key on the device (passkeys, banks, authenticators) prove who you are by signing a challenge; the server only keeps the public key. After the proof, a session (cookie or token) avoids repeating the signature on every request. SSH uses the same trick: the server proves itself to you, then you prove yourself to it.
Três promessas e um ingredienteThree promises and one ingredient
Criptografia não é uma coisa só: é um conjunto de ferramentas que entregam promessas diferentes. Saber qual promessa você quer evita usar a ferramenta errada.Cryptography is not one thing: it is a toolbox whose tools deliver different promises. Knowing which promise you want avoids using the wrong tool.
| PromessaPromise | SignificaMeans | FerramentaTool |
|---|---|---|
| Sigilo (confidencialidade)Secrecy (confidentiality) | Só quem deve consegue ler.Only the intended people can read it. | Cifra (simétrica ou assimétrica)Cipher (symmetric or asymmetric) |
| IntegridadeIntegrity | Ninguém alterou o dado no caminho.Nobody changed the data on the way. | Hash, MAC, assinaturaHash, MAC, signature |
| AutenticidadeAuthenticity | Veio mesmo de quem diz que enviou.It really came from who says sent it. | Assinatura digital, certificadoDigital signature, certificate |
O ingrediente: o hashThe ingredient: the hash
Um hash transforma qualquer dado em um resumo de tamanho fixo. Mesma entrada, mesmo resumo; mudou um caractere, o resumo muda por inteiro; e não há caminho de volta. Ele não esconde nada (não é cifra): serve de impressão digital, e por isso aparece dentro das assinaturas, dos certificados e das senhas guardadas.A hash turns any data into a fixed-size digest. Same input, same digest; change one character and the whole digest changes; and there is no way back. It hides nothing (it is not a cipher): it works as a fingerprint, which is why it shows up inside signatures, certificates and stored passwords.
Chave simétrica: um segredo, dois ladosSymmetric key: one secret, two sides
É a ideia mais antiga: a mesma chave cifra e decifra. Pense em um cofre com uma só chave, da qual existem duas cópias.It is the oldest idea: the same key encrypts and decrypts. Think of a safe with a single key, of which there are two copies.
| AlgoritmoAlgorithm | Para que serveWhat it is for | NotaNote |
|---|---|---|
| AES (128/256 bits) | Padrão de fato para cifrar dados: arquivos, discos, TLS.The de facto standard for encrypting data: files, disks, TLS. | Usado em modos autenticados como GCM, que também detectam alteração.Used in authenticated modes such as GCM, which also detect tampering. |
| ChaCha20-Poly1305 | Alternativa moderna ao AES, rápida mesmo sem hardware dedicado (celulares).Modern alternative to AES, fast even without dedicated hardware (phones). | Presente no TLS 1.3 e no SSH.Present in TLS 1.3 and SSH. |
| HMAC (ex.: HMAC-SHA-256) | Não cifra: prova integridade e autoria entre quem divide o segredo.Does not encrypt: proves integrity and origin between parties that share the secret. | É como as requisições da AWS (SigV4) são assinadas com a secret key.It is how AWS requests (SigV4) are signed with the secret key. |
Chaves pública e privadaPublic and private keys
Aqui a chave vem em par, gerado junto por uma conta matemática: o que uma chave faz, só a outra desfaz. Uma você espalha (pública); a outra nunca sai de você (privada). Descobrir a privada a partir da pública é inviável com os tamanhos usados hoje.Here the key comes as a pair, generated together by a mathematical operation: what one key does, only the other undoes. You spread one (public); the other never leaves you (private). Deriving the private key from the public one is infeasible at today’s key sizes.
Dois usos opostos do mesmo parTwo opposite uses of the same pair
| CifrarEncrypt | AssinarSign | |
|---|---|---|
| Quem usa a privadaWho uses the private key | Destinatário, para lerRecipient, to read | Autor, para assinarAuthor, to sign |
| Quem usa a públicaWho uses the public key | Qualquer um, para cifrarAnyone, to encrypt | Qualquer um, para verificarAnyone, to verify |
| GaranteGuarantees | SigiloSecrecy | Autenticidade e integridadeAuthenticity and integrity |
Algoritmos que você encontraAlgorithms you will meet
| AlgoritmoAlgorithm | FazDoes | Onde apareceWhere you see it | NotaNote |
|---|---|---|---|
| RSA | Cifrar e assinarEncrypt and sign | Certificados mais antigos, chaves SSH antigas, JWT RS256Older certificates, older SSH keys, JWT RS256 | Chaves grandes (2048 bits no mínimo; 3072 ou 4096 para folga). Mais lento e mais pesado.Large keys (2048 bits at least; 3072 or 4096 for margin). Slower and heavier. |
| ECDSA (curvas P-256, P-384) | AssinarSign | Certificados TLS, JWT ES256, passkeysTLS certificates, JWT ES256, passkeys | Chaves curtas para a mesma força que o RSA.Short keys for the same strength as RSA. |
| Ed25519 | AssinarSign | Chaves SSH modernas, assinatura de commitsModern SSH keys, commit signing | Rápido, chaves pequenas e poucas armadilhas de uso. Padrão recomendado para novas chaves SSH.Fast, small keys and few pitfalls. The recommended default for new SSH keys. |
| X25519 / ECDH | Acordar uma chave compartilhadaAgree on a shared key | TLS 1.3, SSHTLS 1.3, SSH | Não cifra nem assina: só produz o segredo comum (veja a seção de TLS).Neither encrypts nor signs: it only produces the common secret (see the TLS section). |
Assinatura digital passo a passoDigital signature step by step
A assinatura responde duas perguntas ao mesmo tempo: quem fez isto e se algo mudou desde então. Ela não esconde o conteúdo; qualquer um lê, e qualquer um confere.A signature answers two questions at once: who made this and whether anything changed since. It does not hide the content; anyone can read it, and anyone can check it.
- Em um JWT: o emissor assina cabeçalho + payload com a chave privada (
RS256,ES256); quem recebe baixa as chaves públicas do emissor (o endereçojwks_urido documento de descoberta do OIDC) e verifica. Foi assim que a AWS confiou no token do GitHub Actions.In a JWT: the issuer signs header + payload with the private key (RS256,ES256); the receiver downloads the issuer’s public keys (thejwks_uriaddress in the OIDC discovery document) and verifies. That is how AWS trusted the GitHub Actions token. - Em um commit do Git: você assina com a privada; o GitHub mostra “Verified” ao conferir com a pública cadastrada na sua conta.In a Git commit: you sign with the private key; GitHub shows “Verified” after checking against the public key registered on your account.
- Em um certificado TLS: a autoridade certificadora assina “esta chave pública pertence a este domínio”.In a TLS certificate: the certificate authority signs “this public key belongs to this domain”.
HS256 existe um segredo compartilhado (HMAC): quem verifica também consegue forjar. Com RS256/ES256, só o dono da privada assina. Sempre fixe o algoritmo esperado ao verificar (RFC 8725).HS256 is something else. In an HS256 JWT there is a shared secret (HMAC): whoever verifies can also forge. With RS256/ES256, only the private-key owner signs. Always pin the expected algorithm when verifying (RFC 8725).Juntando tudo: troca de chaves, TLS e certificadosPutting it together: key exchange, TLS and certificates
A assimétrica é mais lenta e só trata blocos pequenos; a simétrica é rápida e cuida de qualquer volume, mas precisa de uma chave combinada. A solução é híbrida: use a assimétrica para combinar uma chave e a simétrica para proteger os dados. É assim no HTTPS e no SSH.Asymmetric is slower and handles only small blocks; symmetric is fast and handles any volume, but needs an agreed key. The solution is hybrid: use asymmetric to agree on a key and symmetric to protect the data. That is how HTTPS and SSH work.
Acordar uma chave em público: Diffie-HellmanAgreeing on a key in public: Diffie-Hellman
Duas partes trocam mensagens à vista de todos e, no fim, cada uma calcula o mesmo segredo sem que ele tenha trafegado. A analogia das tintas mostra a intuição: misturar é fácil, desmisturar é inviável.Two parties exchange messages in plain sight and, at the end, each computes the same secret without it ever having travelled. The paint analogy shows the intuition: mixing is easy, unmixing is infeasible.
O handshake do TLS 1.3The TLS 1.3 handshake
Certificados: quem garante que a chave pública é do site?Certificates: who guarantees the public key belongs to the site?
Se o seu navegador aceitasse qualquer chave pública enviada pelo servidor, um intermediário poderia mandar a dele. O certificado resolve: é a chave pública do site mais o nome do domínio, assinada por uma autoridade (CA) em quem o sistema já confia. As raízes confiáveis vêm instaladas no sistema operacional e no navegador.If your browser accepted any public key the server sent, a man in the middle could send its own. The certificate fixes this: it is the site’s public key plus the domain name, signed by an authority (CA) the system already trusts. The trusted roots ship with the operating system and the browser.
Apps com a chave privada no aparelhoApps with the private key on the device
Passkeys, apps de banco, autenticadores e chaves de segurança seguem o mesmo desenho: o aparelho gera o par, guarda a privada e entrega ao servidor só a pública. Daí em diante, entrar é assinar um desafio, não digitar um segredo que o servidor também conhece.Passkeys, banking apps, authenticators and security keys follow the same design: the device generates the pair, keeps the private key and gives the server only the public key. From then on, signing in is signing a challenge, not typing a secret the server also knows.
1. Cadastro: o par nasce no aparelho1. Enrollment: the pair is born on the device
2. Login: o servidor desafia, o aparelho assina2. Sign-in: the server challenges, the device signs
- Por que um desafio novo a cada vez? Se a assinatura fosse sempre a mesma, quem a interceptasse poderia reenviá-la (ataque de replay). Com um número aleatório inédito, cada resposta só vale uma vez.Why a new challenge every time? If the signature were always the same, whoever intercepted it could resend it (replay attack). With a never-seen random number, each answer is good only once.
- Por que a biometria não vai para o servidor? Ela só autoriza o chip a usar a chave, localmente. O servidor recebe uma assinatura, nunca a digital nem o rosto.Why does the biometric not go to the server? It only authorizes the chip to use the key, locally. The server receives a signature, never the fingerprint or the face.
- Por que resiste a phishing? No WebAuthn a assinatura cobre o domínio (origem) da página. Uma página falsa em outro domínio não consegue obter uma assinatura que valha para o site verdadeiro.Why is it phishing-resistant? In WebAuthn the signature covers the page’s domain (origin). A fake page on another domain cannot obtain a signature that is valid for the real site.
- E se vazar o banco de dados do servidor? Lá só há chaves públicas, que não permitem assinar. Compare com senhas, em que o vazamento de hashes já ajuda quem ataca.And if the server database leaks? It only holds public keys, which cannot sign. Compare with passwords, where leaked hashes already help the attacker.
Onde fica a chave privadaWhere the private key lives
| PlataformaPlatform | CofreVault | ComportamentoBehavior |
|---|---|---|
| iPhone / Mac | Secure Enclave + KeychainSecure Enclave + Keychain | Chaves podem ser geradas dentro do Enclave e não saem dele; o app só pede a assinatura.Keys can be generated inside the Enclave and never leave it; the app only requests the signature. |
| Android | Android Keystore (TEE ou StrongBox)Android Keystore (TEE or StrongBox) | Chaves protegidas por hardware, marcadas como não exportáveis; uso pode exigir biometria.Hardware-backed keys, marked non-exportable; use can require biometrics. |
| Windows / Linux | TPMTPM | Chip na placa-mãe que guarda e usa chaves sem entregá-las.Chip on the motherboard that stores and uses keys without handing them out. |
| Chave de segurança | YubiKey e similares (FIDO2)YubiKey and similar (FIDO2) | Hardware dedicado: a chave nunca está no seu computador e vale em vários aparelhos.Dedicated hardware: the key is never on your computer and works across devices. |
| Gerenciador de senhas | Cofre sincronizadoSynced vault | Passkeys sincronizadas entre aparelhos: mais conveniência, e a segurança passa a depender da conta do gerenciador.Passkeys synced across devices: more convenience, and security now depends on the manager’s account. |
E depois do login: a sessãoAfter sign-in: the session
Assinar um desafio a cada clique seria inviável (e irritante: uma biometria por requisição). Por isso a prova por chave serve para abrir uma sessão, e a sessão vale por um tempo.Signing a challenge on every click would be impractical (and annoying: one biometric prompt per request). So the key proof is used to open a session, and the session lasts for a while.
| Sessão com ID opaco (cookie)Opaque session ID (cookie) | Tokens (access + refresh, JWT)Tokens (access + refresh, JWT) | |
|---|---|---|
| O que o cliente guardaWhat the client holds | Um ID aleatório sem significado.A random ID with no meaning. | Um token assinado com claims dentro.A signed token with claims inside. |
| Onde está o estadoWhere the state lives | No servidor (memória, Redis, banco).On the server (memory, Redis, database). | No próprio token; o servidor só verifica a assinatura.In the token itself; the server only verifies the signature. |
| Encerrar à forçaForce-ending it | Fácil: apaga o ID no servidor.Easy: delete the ID on the server. | Mais difícil: o token vale até expirar; por isso o access token é curto e há refresh token.Harder: the token is valid until it expires; hence a short access token and a refresh token. |
| CuidadosCare points | HttpOnly, Secure, SameSite; renovar o ID após o login.HttpOnly, Secure, SameSite; renew the ID after login. | Fixar o algoritmo, validar iss, aud, exp; guardar o refresh com mais cuidado.Pin the algorithm, validate iss, aud, exp; guard the refresh token more carefully. |
Como as sessões, o OAuth e o OIDC se encaixam nisso está em Login e autenticação, e os detalhes de cookies e JWT do lado de quem constrói o app estão em Apps web seguros.How sessions, OAuth and OIDC fit in is covered in Sign-in and authentication, and the cookie and JWT details from the app builder’s side are in Secure web apps.
Como o SSH funcionaHow SSH works
SSH (Secure Shell) abre um canal cifrado até outra máquina para shell remoto, execução de comandos, transferência de arquivos (scp, sftp) e túneis. É a seção anterior aplicada: acordo de chave efêmera, assinaturas, chaves públicas e privadas, e um túnel simétrico.SSH (Secure Shell) opens an encrypted channel to another machine for a remote shell, running commands, file transfer (scp, sftp) and tunnels. It is the previous sections applied: ephemeral key agreement, signatures, public and private keys, and a symmetric tunnel.
As três camadasThe three layers
Quem confia em quem: os arquivosWho trusts whom: the files
O SSH tem duas verificações, uma em cada sentido, e cada uma usa um arquivo diferente. Confundi-las é a origem da maioria dos erros.SSH has two checks, one in each direction, and each uses a different file. Mixing them up is the source of most errors.
| PerguntaQuestion | Quem verificaWho checks | ArquivoFile | Se falharIf it fails |
|---|---|---|---|
| “Este servidor é mesmo o servidor?”“Is this server really the server?” | Você (cliente)You (client) | ~/.ssh/known_hosts~/.ssh/known_hosts | Aviso “REMOTE HOST IDENTIFICATION HAS CHANGED”“REMOTE HOST IDENTIFICATION HAS CHANGED” warning |
| “Esta pessoa pode entrar?”“May this person log in?” | ServidorServer | ~/.ssh/authorized_keys~/.ssh/authorized_keys | Permission denied (publickey)Permission denied (publickey) |
O handshake, passo a passoThe handshake, step by step
Mão na massaHands-on
# 1. generate the pair: id_ed25519 (private) and id_ed25519.pub (public)
ssh-keygen -t ed25519 -C "gustavo@laptop"
# 2. show the fingerprint of the public key
ssh-keygen -lf ~/.ssh/id_ed25519.pub
# 3. install the public key on the server (it goes into ~/.ssh/authorized_keys)
ssh-copy-id -i ~/.ssh/id_ed25519.pub ana@server.example.com
# 4. sign in: the private key signs the challenge, it is never sent
ssh ana@server.example.com
# 5. debug: -v shows every key offered and every step
ssh -v ana@server.example.com
- Defina uma passphrase ao gerar a chave: ela cifra o arquivo da privada no disco. Sem ela, quem copiar o arquivo ganha o acesso.Set a passphrase when generating the key: it encrypts the private-key file on disk. Without it, whoever copies the file gets the access.
- Permissões importam:
chmod 700 ~/.sshechmod 600na privada e noauthorized_keys. O SSH recusa chaves legíveis por outros.Permissions matter:chmod 700 ~/.sshandchmod 600on the private key and onauthorized_keys. SSH refuses keys readable by others. - Uma chave por aparelho: assim, perdeu o notebook, remova só a pública dele dos servidores.One key per device: that way, if you lose the laptop, you remove only its public key from the servers.
Endurecendo o servidorHardening the server
# /etc/ssh/sshd_config (check the manual for your distribution)
PubkeyAuthentication yes
PasswordAuthentication no # keys only: removes password guessing
PermitRootLogin no # sign in as a normal user, then use sudo
Depois de alterar, recarregue o serviço (sshd ou ssh, conforme a distribuição) e teste numa segunda sessão antes de fechar a primeira: um erro aqui pode trancar você fora.After changing it, reload the service (sshd or ssh, depending on the distribution) and test in a second session before closing the first: a mistake here can lock you out.
ssh-agent, bastion e ProxyJumpssh-agent, bastion and ProxyJump
# start an agent and load the key (the passphrase is asked once)
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
ssh-add -l # lists the keys the agent holds
# reach an internal server through a bastion, without forwarding the agent
ssh -J ana@bastion.example.com ana@10.0.1.20
SSH com o GitHubSSH with GitHub
Cadastre a pública em Settings → SSH and GPG keys e teste com ssh -T git@github.com. O mesmo par pode também assinar commits (Git 2.34 ou mais novo).Register the public key under Settings → SSH and GPG keys and test with ssh -T git@github.com. The same pair can also sign commits (Git 2.34 or newer).
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
Onde isso aparece no dia a diaWhere this shows up day to day
| SituaçãoSituation | Quem tem a privadaWho holds the private key | O que a pública fazWhat the public key does | Parte simétricaSymmetric part |
|---|---|---|---|
| HTTPSHTTPS | O servidor (chave do certificado)The server (certificate key) | Navegador verifica a assinatura do handshakeBrowser verifies the handshake signature | Chave de sessão do TLS (AES-GCM, ChaCha20)TLS session key (AES-GCM, ChaCha20) |
| SSHSSH | Você (login) e o servidor (host key)You (login) and the server (host key) | authorized_keys e known_hostsauthorized_keys and known_hosts | Túnel cifrado da sessãoThe session’s encrypted tunnel |
| Passkey / app de bancoPasskey / banking app | O chip do seu aparelhoYour device’s chip | O servidor verifica a assinatura do desafioThe server verifies the challenge signature | Sessão (cookie/token) e TLSSession (cookie/token) and TLS |
| JWT / OIDCJWT / OIDC | O provedor de identidade (GitHub, Google)The identity provider (GitHub, Google) | Quem recebe o token baixa a pública (JWKS) e verificaWhoever receives the token downloads the public key (JWKS) and verifies | TLS na chamadaTLS on the call |
| Commit assinadoSigned commit | VocêYou | GitHub verifica e mostra “Verified”GitHub verifies and shows “Verified” | —— |
| Chaves de acesso da AWSAWS access keys | Ninguém: é simétrico (HMAC). A secret key fica em dois lugares.Nobody: it is symmetric (HMAC). The secret key lives in two places. | —— | A requisição é assinada com HMAC-SHA-256 (SigV4)The request is signed with HMAC-SHA-256 (SigV4) |
GlossárioGlossary
| TermoTerm | O que éWhat it is |
|---|---|
| Criptografia | Técnicas matemáticas para proteger sigilo, integridade e autenticidade.Mathematical techniques to protect secrecy, integrity and authenticity. |
| Texto claro / texto cifrado | O dado legível e o dado embaralhado pela cifra.The readable data and the data scrambled by the cipher. |
| Chave | Um número (ou bytes) que controla a cifra. Quem tem a chave certa desfaz o embaralhamento.A number (or bytes) that controls the cipher. Whoever holds the right key undoes the scrambling. |
| Chave pública / privada | As duas metades de um par. A pública pode ser distribuída; a privada nunca sai do dono.The two halves of a pair. The public one may be shared; the private one never leaves its owner. |
| Hash / resumo (digest) | Impressão digital de tamanho fixo, sem volta. Ex.: SHA-256.Fixed-size fingerprint, no way back. E.g. SHA-256. |
| Assinatura digital | Prova de autoria e integridade feita com a chave privada e conferida com a pública.Proof of authorship and integrity made with the private key and checked with the public one. |
| Certificado (X.509) | Chave pública + identidade (domínio), assinada por uma CA.Public key + identity (domain), signed by a CA. |
| CA (autoridade certificadora) | Entidade em quem o sistema confia para assinar certificados. Ex.: Let’s Encrypt.Entity the system trusts to sign certificates. E.g. Let’s Encrypt. |
| Desafio (nonce) | Valor aleatório usado uma única vez para que a resposta não possa ser reaproveitada.Random value used only once so the answer cannot be reused. |
| Chave efêmera / forward secrecy | Chave criada só para uma conexão. Garante que roubar chaves futuras não decifra conversas passadas.Key created just for one connection. Ensures that stealing later keys does not decrypt past conversations. |
| Impressão digital (fingerprint) | Hash curto de uma chave pública, para conferir a olho. Ex.: SHA256:… no SSH.Short hash of a public key, for checking by eye. E.g. SHA256:… in SSH. |
| Passphrase | Senha que cifra o arquivo da chave privada no disco.Password that encrypts the private-key file on disk. |
| Enclave / TPM / StrongBox | Hardware seguro que guarda a chave privada e assina sem entregá-la.Secure hardware that keeps the private key and signs without handing it out. |
| Sessão | Estado “você já entrou”, guardado no servidor ou num token, que dispensa nova prova a cada requisição.The “you are already in” state, kept on the server or in a token, which avoids a new proof on every request. |
| TOFU | Trust on first use: confiar na chave vista na primeira conexão e alertar se mudar depois.Trust on first use: trust the key seen on the first connection and warn if it changes later. |
Erros comuns e como resolverCommon errors and how to fix them
| SintomaSymptom | Causa provávelLikely cause | O que fazerWhat to do |
|---|---|---|
Permission denied (publickey) | A pública não está no servidor, o usuário está errado ou o SSH ofereceu outra chave.The public key is not on the server, the user is wrong, or SSH offered another key. | Rode ssh -v e veja as chaves oferecidas; confira authorized_keys, o nome do usuário e use -i ou IdentityFile.Run ssh -v and look at the keys offered; check authorized_keys, the user name and use -i or IdentityFile. |
UNPROTECTED PRIVATE KEY FILE! | A privada está legível por outros usuários.The private key is readable by other users. | chmod 600 ~/.ssh/id_ed25519 e chmod 700 ~/.ssh.chmod 600 ~/.ssh/id_ed25519 and chmod 700 ~/.ssh. |
REMOTE HOST IDENTIFICATION HAS CHANGED! | A chave do servidor mudou: reinstalação, IP reaproveitado... ou um intermediário.The server key changed: reinstall, reused IP... or a man in the middle. | Não ignore. Confirme com quem administra o servidor; só então ssh-keygen -R host e reconecte.Do not ignore it. Confirm with whoever runs the server; only then ssh-keygen -R host and reconnect. |
Too many authentication failures | O agent oferece chaves demais antes da certa.The agent offers too many keys before the right one. | Use IdentitiesOnly yes e IdentityFile no ~/.ssh/config.Use IdentitiesOnly yes and IdentityFile in ~/.ssh/config. |
| Colei a pública no lugar da privada (ou o contrário) | Confusão entre id_ed25519 e .pub.Mixing up id_ed25519 and .pub. | A .pub é a que se compartilha. Para conferir se um par combina: ssh-keygen -y -f id_ed25519 imprime a pública correspondente.The .pub is the one you share. To check a pair matches: ssh-keygen -y -f id_ed25519 prints the matching public key. |
Load key … invalid format | Arquivo da privada corrompido: quebra de linha trocada, cabeçalho cortado, falta a linha final.Corrupted private-key file: changed line endings, cut header, missing final newline. | Recopie o arquivo inteiro, sem editar, ou gere um novo par.Copy the whole file again, unedited, or generate a new pair. |
| A privada foi parar no repositório, num chat ou num log | Vazamento: considere-a comprometida.Leak: consider it compromised. | Remova a pública dos servidores e da conta do GitHub, gere um par novo. Apagar o commit não basta: o histórico e os clones guardam a cópia.Remove the public key from servers and the GitHub account, generate a new pair. Deleting the commit is not enough: history and clones keep the copy. |
Navegador: NET::ERR_CERT_COMMON_NAME_INVALID ou certificado expirado | O nome no certificado não cobre o domínio acessado, ou a validade acabou.The name in the certificate does not cover the domain visited, or the validity ended. | Confira os nomes (SAN) e a data; renove; instale também o certificado intermediário.Check the names (SAN) and the date; renew; also install the intermediate certificate. |
| Tentei “cifrar com a privada” para proteger dados | Confundir assinatura com cifragem.Mixing up signing with encrypting. | Para sigilo, cifre com a pública do destinatário (ou use uma chave simétrica). Para provar autoria, assine.For secrecy, encrypt with the recipient’s public key (or use a symmetric key). To prove authorship, sign. |
| JWT aceito mesmo com a assinatura alterada | O verificador aceita alg: none ou troca RS256 por HS256 usando a pública como segredo.The verifier accepts alg: none or swaps RS256 for HS256 using the public key as the secret. | Fixe o algoritmo esperado na verificação e use bibliotecas mantidas (RFC 8725).Pin the expected algorithm when verifying and use maintained libraries (RFC 8725). |
| Perdi o celular com a passkey | A privada ficou no aparelho.The private key was on the device. | Use outra passkey ou os códigos de backup, e revogue a credencial antiga no servidor.Use another passkey or the backup codes, and revoke the old credential on the server. |
Cola e revisãoCheat sheet and review
ColaCheat sheet
| Quero…I want… | FaçaDo |
|---|---|
| que ninguém leia os dados no caminhonobody to read the data on the way | Cifre: TLS no tráfego, AES-GCM em dados em repouso.Encrypt: TLS for traffic, AES-GCM for data at rest. |
| provar que um arquivo ou token veio de mimto prove a file or token came from me | Assine com a privada; quem recebe verifica com a pública.Sign with the private key; the receiver verifies with the public one. |
| detectar se algo foi alteradoto detect tampering | Compare hashes (ou use assinatura/MAC se houver adversário).Compare hashes (or use a signature/MAC if there is an adversary). |
| entrar num servidor por SSHto log in to a server over SSH | ssh-keygen -t ed25519, ssh-copy-id, desligar senha no servidor.ssh-keygen -t ed25519, ssh-copy-id, turn passwords off on the server. |
| login sem senha em um apppassword-free sign-in in an app | Passkey/WebAuthn: o aparelho assina um desafio; guarde só a pública.Passkey/WebAuthn: the device signs a challenge; store only the public key. |
| manter o usuário logado sem pedir assinatura sempreto keep the user signed in without asking for a signature every time | Sessão com cookie seguro ou token curto + refresh; reautentique em ações sensíveis.Session with a secure cookie or short token + refresh; re-authenticate on sensitive actions. |
| conferir um servidor SSH novoto check a new SSH server | Compare a impressão (fingerprint) por outro canal antes de aceitar.Compare the fingerprint over another channel before accepting. |
Perguntas de revisãoReview questions
| PerguntaQuestion | RespostaAnswer |
|---|---|
| Por que o TLS e o SSH combinam criptografia assimétrica e simétrica?Why do TLS and SSH combine asymmetric and symmetric cryptography? | A assimétrica resolve combinar uma chave em público (e prova identidade), mas é lenta; a simétrica é rápida para o volume de dados. Usa-se a primeira para acordar a chave e a segunda para os dados.Asymmetric solves agreeing on a key in public (and proves identity) but is slow; symmetric is fast for the volume of data. The first agrees on the key, the second carries the data. |
| Num login por chave no aparelho, o que trafega e o que nunca sai do aparelho?In a device-key sign-in, what travels and what never leaves the device? | Trafegam o desafio e a assinatura (e, no cadastro, a chave pública). A chave privada e a biometria nunca saem do aparelho; o servidor só verifica com a pública.The challenge and the signature travel (and, at enrollment, the public key). The private key and the biometric never leave the device; the server only verifies with the public key. |
| Por que existe a sessão depois da assinatura, e qual o risco dela?Why does the session exist after the signature, and what is its risk? | Para não assinar a cada requisição. O risco: é um portador, e um cookie ou token roubado vale até expirar; por isso prazos curtos, revogação e step-up.To avoid signing on every request. The risk: it is a bearer, and a stolen cookie or token works until it expires; hence short lifetimes, revocation and step-up. |
O que known_hosts e authorized_keys provam, cada um?What do known_hosts and authorized_keys each prove? | known_hosts: você confere que o servidor é o mesmo de antes. authorized_keys: o servidor confere que a sua chave está autorizada a entrar.known_hosts: you check that the server is the same as before. authorized_keys: the server checks that your key is allowed in. |
- RFC 8446 · TLS 1.3
- RFC 5280 · Internet X.509 PKI Certificate and CRL Profile
- RFC 7748 · Elliptic Curves for Security (X25519)
- RFC 8032 · Edwards-Curve Digital Signature Algorithm (Ed25519)
- RFC 8017 · PKCS #1: RSA Cryptography Specifications
- RFC 4251 · The Secure Shell (SSH) Protocol Architecture
- RFC 4252 · The SSH Authentication Protocol
- RFC 4253 · The SSH Transport Layer Protocol
- RFC 4254 · The SSH Connection Protocol
- RFC 8725 · JSON Web Token Best Current Practices
- RFC 9449 · OAuth 2.0 Demonstrating Proof of Possession (DPoP)
- W3C · Web Authentication (WebAuthn)
- OpenSSH · Manual pages
- GitHub Docs · Connecting to GitHub with SSH
- Apple · Protecting keys with the Secure Enclave
- Android · Keystore system
- Let’s Encrypt · How it works
- OWASP · Session Management Cheat Sheet