SSH(Secure Shell)是一种网络协议,用于在不安全的网络中为远程登录和其他安全网络服务提供安全保障。SSH密钥对是通过ssh-keygen
工具生成的一对加密密钥:公钥和私钥。本文将详细介绍如何使用ssh-keygen
生成SSH密钥对,并解释其工作原理。
当客户端尝试通过SSH连接到服务器时,服务器会要求客户端证明它拥有与公钥对应的私钥。这通过一种称为“非对称加密”的技术实现。
确保你已经安装了OpenSSH客户端。大多数Linux和macOS系统默认都已安装。Windows用户可以通过安装Windows Subsystem for Linux (WSL) 或者直接使用Git Bash来获得类似的环境。
执行以下命令以启动密钥生成过程:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
这里:
-t rsa
指定密钥类型为RSA。-b 4096
设置密钥长度为4096位,增加安全性。-C "your_email@example.com"
提供了一个可选的注释字段,通常是你自己的电子邮件地址,方便识别。系统会提示你输入保存密钥文件的位置,默认路径通常是~/.ssh/id_rsa
。如果接受默认值,只需按回车键即可。
Enter file in which to save the key (/home/your_user/.ssh/id_rsa):
接下来,系统会让你为私钥设置一个密码(passphrase)。这是一个额外的安全层,即使你的私钥被盗,攻击者也需要知道这个密码才能使用它。
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
注意:如果你不想设置密码,可以直接按回车跳过。
成功后,你会看到类似以下的信息:
Your identification has been saved in /home/your_user/.ssh/id_rsa.
Your public key has been saved in /home/your_user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx your_email@example.com
The key's randomart image is:
+---[RSA 4096]----+
| |
| . |
| + o |
| . B * |
| o = S |
| + + o |
| . = . |
| E . |
| . |
+----[SHA256]-----+
假设你想使用新生成的密钥对连接到远程服务器,你需要将公钥复制到该服务器上。可以使用ssh-copy-id
命令简化这一过程:
ssh-copy-id user@remote_host
如果没有ssh-copy-id
命令,也可以手动完成:
cat ~/.ssh/id_rsa.pub
~/.ssh/authorized_keys
文件,将公钥粘贴进去。现在,尝试无密码登录到你的远程服务器:
ssh user@remote_host
如果一切配置正确,你应该能够顺利连接而无需输入密码。