MacでのSSH Keyの作成方法

MacOSでのSSH Keyの作成方法です。

次のコマンドをターミナルで実行すると、3072bitのRSAキーが作成されます。(※2025年7月4日時点)

ssh-keygen

しかし、RSAのアルゴリズムは非推奨となっており、新しい暗号アルゴリズムであるECDSAが推奨されているようです。

アルゴリズムを指定するには、次のように-tオプションで指定できます。また特定のアルゴリズムでは、-bオプションで長さを指定できます。

ssh-keygen -t ecdsa -b 521

以下は、ssh-keygenを実行した際のメッセージです。

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): 
Created directory '/Users/xxx/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/xxx/.ssh/id_rsa
Your public key has been saved in /Users/xxx/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx user@hostname
The key's randomart image is:
+---[RSA 3072]----+
〜 略 〜
+----[SHA256]-----+

以下の2つの入力は、記述せずにエンターのみで実行可能です。

Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 

ただ2つ目のパスフレーズ(Enter passphrase)はセキュリティを高めるために入力が推奨されます。

/Users/xxx/.sshディレクトリが存在しない場合は.sshディレクトリが作成されて、.sshディレクトリに公開鍵と秘密鍵が保存されます。

公開鍵のファイル末尾に入るuser@hostnameはMacのコンピューター名から記述が入ります。気になる方は、-Cオプションで指定することが可能です。

ssh-keygen -C "your_email@example.com"

すでに公開鍵と秘密鍵がある状態でssh-keygenを実行すると、上書きをするか確認が入ります。

/Users/xxx/.ssh/id_rsa already exists.
Overwrite (y/n)? y

以下の入力は、保存するファイル名およびパスを入力できます。

Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): 

ファイル名のみ入力すると、/Users/xxx/ディレクトリにファイル名がxxxの秘密鍵とxxx.pubの公開鍵が作成されます。

そのため、.sshディレクトリにexampleというファイル名で鍵を作成したい場合は、次のように入力します。

Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/xxx/.ssh/example

参考

How to Create SSH Keys with OpenSSH on MacOS or Linux
https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/create-with-openssh

Generating a new SSH key and adding it to the ssh-agent
https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

How to Use ssh-keygen to Generate a New SSH Key?
https://www.ssh.com/academy/ssh/keygen

目次