How to Generate, Copy, and Manage Public and Private Keys on Windows and Ubuntu

Public and private key pairs are essential for securing connections, authentication, and encryption, especially when using SSH (Secure Shell). In this article, we will go over how to generate, copy, and manage these keys on both Windows and Ubuntu.

1. Generating SSH Keys

On Windows (Using PowerShell or Git Bash)

  1. Install the OpenSSH Client:
  • Open PowerShell as Administrator.
  • Check if OpenSSH is installed with the following command:
    powershell Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Client*'
  • If it’s not installed, add it with:
    powershell Add-WindowsCapability -Online -Name OpenSSH.Client*
  1. Generate SSH Key Pair:
  • In PowerShell or Git Bash, run the following command to generate the keys (replace email@example.com with your email):
    bash ssh-keygen -t rsa -b 4096 -C "email@example.com"
  • When prompted, choose a location to save the key (press Enter to use the default location).
  • Set a passphrase to protect the private key (optional, but recommended).
  1. Check the Keys:
  • The keys are stored by default in C:\Users\YourUsername\.ssh\:
    • Private key: id_rsa
    • Public key: id_rsa.pub

On Ubuntu (Terminal)

  1. Install OpenSSH:
  • Run the following command to ensure OpenSSH is installed:
    bash sudo apt update sudo apt install openssh-client
  1. Generate SSH Key Pair:
  • In the terminal, execute the following command to generate the key pair (replace email@example.com with your email):
    bash ssh-keygen -t rsa -b 4096 -C "email@example.com"
  • Choose where to save the key or press Enter to use the default location.
  • Set a passphrase to protect the private key (optional, but recommended).
  1. Check the Keys:
  • The keys will be stored by default in ~/.ssh/:
    • Private key: id_rsa
    • Public key: id_rsa.pub

2. Copy the Public Key to a Server

Windows and Ubuntu

  1. Using ssh-copy-id:
  • In the terminal, you can automatically copy your public key to a remote server using:
    bash ssh-copy-id user@remote_host
  • This adds the public key to the ~/.ssh/authorized_keys file on the remote server.
  1. Manual Copy:
  • If ssh-copy-id is unavailable, manually copy the public key:
    • Display the public key:
      bash cat ~/.ssh/id_rsa.pub
    • On the remote server, edit the ~/.ssh/authorized_keys file and paste the copied public key:
      bash nano ~/.ssh/authorized_keys

3. Managing Keys

List Active SSH Keys:

  • On both Windows and Ubuntu, use the following command to list keys loaded in the SSH agent:
  ssh-add -l

Add a Key to the SSH Agent:

  • To avoid entering the passphrase for each login, add the key to the SSH agent:
  ssh-add ~/.ssh/id_rsa

Remove a Key from the SSH Agent:

  • If you need to remove a key from the agent, use:
  ssh-add -d ~/.ssh/id_rsa

Configure Multiple Keys:

  • If you use multiple keys for different servers, create a configuration file (~/.ssh/config) to manage them:
  Host server1
      HostName server1.example.com
      User user1
      IdentityFile ~/.ssh/id_rsa_server1

  Host server2
      HostName server2.example.com
      User user2
      IdentityFile ~/.ssh/id_rsa_server2

Conclusion

Generating, copying, and managing public and private keys is essential for ensuring secure SSH connections. This article showed how to perform these tasks on both Windows and Ubuntu, as well as tips for managing multiple keys. This improves both security and convenience when using SSH to access remote servers.

Summary of Commands

CommandDescription
ssh-keygen -t rsa -b 4096Generates a 4096-bit RSA key pair
ssh-copy-id user@remote_hostCopies the public key to the remote server
ssh-add ~/.ssh/id_rsaAdds the key to the SSH agent
ssh-add -lLists keys loaded in the SSH agent
ssh-add -d ~/.ssh/id_rsaRemoves the key from the SSH agent
nano ~/.ssh/authorized_keysEdits the authorized keys file

This guide will help you manage SSH keys effectively on both Windows and Ubuntu systems.

Aqui está o artigo reescrito de forma mais clara e objetiva:


Como Gerar, Copiar e Gerenciar Chaves Públicas e Privadas no Windows e Ubuntu

Chaves públicas e privadas são fundamentais para garantir a segurança de conexões, autenticação e criptografia, especialmente ao usar SSH (Secure Shell). Neste artigo, vamos ver como gerar, copiar e gerenciar essas chaves no Windows e no Ubuntu.

1. Gerar Chaves SSH

No Windows (Usando PowerShell ou Git Bash)

  1. Instalar o OpenSSH Client:
  • Abra o PowerShell como administrador.
  • Verifique se o OpenSSH está instalado com o comando:
    powershell Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Client*'
  • Se não estiver instalado, adicione-o com:
    powershell Add-WindowsCapability -Online -Name OpenSSH.Client*
  1. Gerar o Par de Chaves SSH:
  • No PowerShell ou Git Bash, execute o comando abaixo para gerar as chaves (substitua email@example.com pelo seu email):
    bash ssh-keygen -t rsa -b 4096 -C "email@example.com"
  • Quando solicitado, escolha um local para salvar a chave (pressione Enter para usar o local padrão).
  • Defina uma senha para proteger a chave privada (opcional, mas recomendado).
  1. Verificar as Chaves:
  • As chaves serão armazenadas por padrão em C:\Users\SeuUsuario\.ssh\:
    • Chave privada: id_rsa
    • Chave pública: id_rsa.pub

No Ubuntu (Terminal)

  1. Instalar o OpenSSH:
  • Execute o comando para garantir que o OpenSSH está instalado:
    bash sudo apt update sudo apt install openssh-client
  1. Gerar o Par de Chaves SSH:
  • No terminal, execute o seguinte comando para gerar o par de chaves (substitua email@example.com pelo seu email):
    bash ssh-keygen -t rsa -b 4096 -C "email@example.com"
  • Escolha onde salvar a chave ou pressione Enter para usar o local padrão.
  • Defina uma senha para proteger a chave privada (opcional, mas recomendado).
  1. Verificar as Chaves:
  • As chaves serão salvas por padrão em ~/.ssh/:
    • Chave privada: id_rsa
    • Chave pública: id_rsa.pub

2. Copiar a Chave Pública para o Servidor

Windows e Ubuntu

  1. Usar o ssh-copy-id:
  • No terminal, você pode copiar automaticamente sua chave pública para um servidor remoto usando:
    bash ssh-copy-id user@remote_host
  • Isso adiciona a chave pública ao arquivo ~/.ssh/authorized_keys do servidor remoto.
  1. Copiar Manualmente:
  • Se o ssh-copy-id não estiver disponível, copie a chave pública manualmente:
    • Exiba o conteúdo da chave pública:
      bash cat ~/.ssh/id_rsa.pub
    • No servidor remoto, edite o arquivo ~/.ssh/authorized_keys e cole a chave pública copiada:
      bash nano ~/.ssh/authorized_keys

3. Gerenciar Chaves

Listar Chaves SSH Ativas:

  • No Windows ou Ubuntu, use o comando abaixo para listar as chaves carregadas no agente SSH:
  ssh-add -l

Adicionar uma Chave ao Agente SSH:

  • Para evitar a necessidade de inserir a senha a cada login, adicione a chave ao agente SSH:
  ssh-add ~/.ssh/id_rsa

Remover uma Chave do Agente SSH:

  • Se precisar remover uma chave do agente, use:
  ssh-add -d ~/.ssh/id_rsa

Configurar Múltiplas Chaves:

  • Se você usar várias chaves para diferentes servidores, crie um arquivo de configuração (~/.ssh/config) para gerenciá-las:
  Host server1
      HostName server1.example.com
      User user1
      IdentityFile ~/.ssh/id_rsa_server1

  Host server2
      HostName server2.example.com
      User user2
      IdentityFile ~/.ssh/id_rsa_server2

Conclusão

Gerar, copiar e gerenciar chaves públicas e privadas é uma tarefa essencial para garantir a segurança de conexões SSH. Este artigo mostrou como realizar essas operações tanto no Windows quanto no Ubuntu, além de algumas dicas para gerenciar múltiplas chaves. Isso melhora a segurança e a conveniência no uso do SSH para acessar servidores remotos.

Resumo de Comandos

ComandoDescrição
ssh-keygen -t rsa -b 4096Gera um par de chaves RSA de 4096 bits
ssh-copy-id user@remote_hostCopia a chave pública para o servidor
ssh-add ~/.ssh/id_rsaAdiciona a chave ao agente SSH
ssh-add -lLista as chaves carregadas no agente SSH
ssh-add -d ~/.ssh/id_rsaRemove a chave do agente SSH
nano ~/.ssh/authorized_keysEdita o arquivo de chaves autorizadas

Edvaldo Guimrães Filho Avatar

Published by

Categories:

Leave a comment