AdSense

網頁

2023/6/6

Mac 產生SSH金鑰 generate ssh key

在macOS產生SSH key(SSH金鑰)的方式如下:


範例環境:

  • macOS Ventura 13.0.1


產生SSH key

開啟終端機輸入ssh-keygen -t rsa即可產生SSH key,這邊為RSA key。輸入後的提問直接按Enter使用預設值。

~% sh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/<user>/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/<user>/.ssh/id_rsa
Your public key has been saved in /Users/<user>/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:Ajdanwfj0wSrE2fqky/3jAkonlT4nKZ3x0lTk6fdIi0 <user>@<hostname>.local
The key's randomart image is:
+---[RSA 3072]----+
|        .        |
|         o       |
|    . = * ..     |
|   . = X *+ .    |
|  . o = S.o* .   |
|   + + +ooE + .  |
|  o * =o o o .   |
| o =. o+=+       |
|  +. . ++.o      |
+----[SHA256]-----+

-t參數是指定要生成的key type(金鑰類型),包括dsaecdsaed25519rsa等,差別在於生成金鑰的演算法。

生成的金鑰(公鑰及私鑰)預設放在~/.ssh目錄。後面有.pub的為公鑰(public key)。例如下面的id_rsa是private key;id_rsa.pub是public key。

~% ls ~/.ssh
id_rsa		id_rsa.pub

用文字編輯器開啟id_rsa.pub內容如下。檔案內容開頭為加密類型ssh-rsa中間空一格,後面為一堆亂碼即為公鑰,<user>@<host>為SSH key的comment欄位,通常用來識別SSH key的使用者,預設為mac登入帳號。

id_rsa.pub

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7CioY3J6CAg6OgCvCWLEctvxHCCbkrEG0kyZVwT4nJKkO0CC9cM9EOhr6MDULVcu5zRuHd/l4H7n0oEqh7C2DSl61dZpAPrhlz3HiCtjwVehVCGXr2npS4v2fZsqL4XOjhqRw03xiDcWhHRzpSpxDymTE39AyRW8C1TQBeDniG8CHRlC6ev6en+GC999t2s+GXyVbUMWAHONJnFasQft7HqeixfTeRomkgbC1X3DlvrJbZEWt/ic3TsTPdQL/DOsDCu+5SSYFK8ZbEXKT0rEuvUg1qGf9jl57Zao7oUjwsvxZluOiuif+fBw7m+hk80GtOIRhjuhqtStOgO1Kl/8lu47tZCqlX03sS/yQw4uYLi7Dk6JRTJY77BUwylzXpdIqDuAO1hnB1nshmD73ypMh8Dq4g3764Tn0Ndz3epSfx6AICCMOeOIcYoama9TFVJSGtCmdSQp4Rz9zzlx/eu04EFeV+txlCP340HJvOznw7j0KuiP71s7Q0WfANzBLa3k= <user>@<host>.local

通常SSH key生成後,要把私鑰保存在安全的地方(例如限制訪問權限及密碼的目錄),公鑰則是上傳到要訪問的主機、網站或程式等。


指定SSH key名稱

加上-C參數可設定SSH key comment的使用者名稱,例如ssh-keygen -t rsa -C <username>

例如輸入ssh-keygen -t rsa -C john產生的SSH key的comment即為john

id_rsa.pub

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7CioY3J6CAg6OgCvCWLEctvxHCCbkrEG0kyZVwT4nJKkO0CC9cM9EOhr6MDULVcu5zRuHd/l4H7n0oEqh7C2DSl61dZpAPrhlz3HiCtjwVehVCGXr2npS4v2fZsqL4XOjhqRw03xiDcWhHRzpSpxDymTE39AyRW8C1TQBeDniG8CHRlC6ev6en+GC999t2s+GXyVbUMWAHONJnFasQft7HqeixfTeRomkgbC1X3DlvrJbZEWt/ic3TsTPdQL/DOsDCu+5SSYFK8ZbEXKT0rEuvUg1qGf9jl57Zao7oUjwsvxZluOiuif+fBw7m+hk80GtOIRhjuhqtStOgO1Kl/8lu47tZCqlX03sS/yQw4uYLi7Dk6JRTJY77BUwylzXpdIqDuAO1hnB1nshmD73ypMh8Dq4g3764Tn0Ndz3epSfx6AICCMOeOIcYoama9TFVJSGtCmdSQp4Rz9zzlx/eu04EFeV+txlCP340HJvOznw7j0KuiP71s7Q0WfANzBLa3k= john

指定SSH key檔名

產生SSH key的檔案預設私鑰為~/.ssh/id_rsa,公鑰為~/.ssh/id_rsa.pub。若要修改存放的檔案加上-f來修改。

例如輸入ssh-keygen -t rsa -f ~/.ssh/john_rsa則產生的私鑰為~/.ssh/john_rsa,公鑰為~/.ssh/john_rsa.pub

~% ssh-keygen -t rsa -C john -f ~/.ssh/john_rsa

沒有留言:

AdSense