OpenSSHで使えるRSA鍵ペアをOpenSSLで生成する

OpenSSH 7.1/7.1p1でRSA鍵長は最低1024bitになりました．

* Refusing all RSA keys smaller than 1024 bits (the current minimum
is 768 bits)

https://www.openssh.com/txt/release-7.1

1024bitより短い鍵長の鍵を作ろうとすると怒られます．

$ ssh-keygen -t rsa -b 768
Invalid RSA key length: minimum is 1024 bits

以下のMLで古い機器が1024bitに対応していない場合の相談でOpenSSLでOpenSSHで利用できるRSA鍵ペアが作れるのを知りました．

You can use openssl to generate a shorter key:

$ openssl genprsa -out key.pem 768
$ ssh-keygen -y -f key.pem > key.pub # optional to get public key

This works with a 768-bit RSA key (client: OpenSSH_7.2p2, OpenSSL
1.0.2g; server: OpenSSH_7.2p2, OpenSSL 1.0.2g) but not a 256-bit RSA
key: I can generate the shorter key but the server requires a minimum of
768-bits.

Settable minimum RSA key sizes on the client end for legacy devices.

/index.html (OpenSSL)

使うことがあるかわからないけど手元の環境で試してみました．

opensslでRSA 768の秘密鍵の作成

$ openssl genrsa -out id_rsa768 768
Generating RSA private key, 768 bit long modulus (2 primes)
........+++++++
................................+++++++
e is 65537 (0x010001)

パスフレーズありのRSA 768の秘密鍵の作成

$ openssl genrsa -out id_rsa768 -aes256 768
Generating RSA private key, 768 bit long modulus (2 primes)
..+++++++
..........+++++++
e is 65537 (0x010001)
Enter pass phrase for id_rsa768:
Verifying - Enter pass phrase for id_rsa768:

OpenSSLから書き出された鍵ファイルのパーミッションはumaskに関係なく(0000でも)600になっています :)

秘密鍵の確認

$ openssl rsa -text < id_rsa768

秘密鍵が出来たので続いてペアとなる公開鍵を作ります．
MLの例と同じように ssh-keygen を使うと鍵の長さで怒られます．

$ ssh-keygen -y -f id_rsa768 > id_rsa768.pub
Load key "id_rsa768": Invalid key length

公開鍵もOpenSSLで作ります．

OpenSSL公開鍵を作る

$ openssl rsa -pubout < id_rsa768 > id_rsa768.pub
writing RSA key

公開鍵の確認

$ openssl rsa -text -pubin < id_rsa768.pub

出来上がった鍵ペアでログインを試みると鍵長のせいで認証に失敗

$ ssh -v -i ~/.ssh/id_rsa768 localhost
:
debug1: Trying private key: /home/matoken/.ssh/id_rsa768
Load key "/home/matoken/.ssh/id_rsa768": Invalid key length

てことで使いみちがなさそうですがメモしておきます．
＃今ならed25519使いますしね……．

ちなみに1024bitより長い鍵なら普通に使えてssh-keygenでコメントを書き換えたりパスフレーズを書き換えたりでしました．

RSA 4096の鍵

$ openssl genrsa -out id_rsa4096 -aes256 4096
Generating RSA private key, 4096 bit long modulus (2 primes)
................++++
.....................................................................................................++++
e is 65537 (0x010001)
Enter pass phrase for id_rsa4096:
Verifying - Enter pass phrase for id_rsa4096:
$ ssh-keygen -c -C 'OpenSSL generate key' -f ./id_rsa4096
Enter passphrase:
No existing comment
Comment 'OpenSSL generated key' applied
$ ssh-keygen -p -f ./id_rsa4096
Enter old passphrase:
Key has comment 'OpenSSL generated key'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.

環境

$ dpkg-query -W openssl openssh-client openssh-server
openssh-client 1:8.1p1-2
openssh-server 1:8.1p1-2
openssl 1.1.1d-2
$ lsb_release -dr
Description: Debian GNU/Linux bullseye/sid
Release: unstable
$ uname -m
x86_64