ssh-keygen #
常用命令:
ssh-keygen -t ed25519 -b 2048 -C [email protected] -f ~/.ssh/id_ed25519 -N "password" -q
-t
生成密钥的类型
ssh-keygen -t rsa | ecdsa | ed25519 | rsa
rsa
rsa加密算法。(默认)ecdsa
椭圆曲线加密算法。ed25519
ed25519加密算法。(保密性最高)rsa
rsa加密算法。
-b
生成密钥的大小(单位:字节)
ssh-keygen -b 2048
-C
生成密钥的描述信息,一般为邮箱地址
ssh-keygen -C [email protected]
-f
生成文件的路径,默认路径为~/.ssh/id_rsa/xx
ssh-keygen -f ~/.ssh/id_rsa
-N
生成解析密钥的密码
ssh-keygen -N "password"
-q
生成密钥时不显示任何信息
ssh-keygen -q
ssh逻辑 #
ssh+password实现登陆 #
- 客户端连接上服务器,服务器把公钥发给客户端
- 客户端用服务器公钥加密,上传密码
- 服务器用私钥解密,如果匹配,则连接成功
服务器
持有私钥,客户端
持有公钥。
sequenceDiagram
autonumber
participant s as 服务器(持有私钥)
participant c as 客户端(持有公钥)
rect rgb(199, 237, 204)
s-->>c: 发送公钥
activate c
c-->>s: 上传用公钥加密的密码
deactivate c
s-->>c: 匹配密码,建立连接
end
ssh实现登陆(git等) #
- 服务器发送一段随机字符串,并使用公钥加密
- 客户端使用私钥解密,并返回解密后的信息
- 服务器进行信息对比,如果验证成功,则允许连接
服务器
持有公钥,客户端
持有私钥。
sequenceDiagram
autonumber
participant s as 服务器(持有公钥)
participant c as 客户端(持有私钥)
rect rgb(199, 237, 204)
s-->>c: 发送用公钥加密的随机字符串
activate c
c-->>s: 发送私钥解密后的随机字符串
deactivate c
s-->>c: 随机字符串匹配,建立连接
end
利用ssh实现登陆linux服务器 #
- 通过
ssh-keygen
生成密钥对 - 将公钥文件(xx.pub)中的内容拷贝至服务器的
~/.ssh/authorized_keys
文件中(另起一行) - 将私钥文件添加到客户端的
ssh-agent
中。
ssh-agent bash
ssh-add <私钥位置>
ssh <用户名>@<地址>
常见问题 #
因为修改了私钥默认名称或者默认路径,系统无法找到私钥 #
解决方案如下:
在~/.ssh/config
文件中添加如下内容:
IdentityFile <私钥路径>