How to Verify That a Public SSH Key Matches Its Private Key
Locally extract the public portion from a private OpenSSH key, compare SHA-256 fingerprints, and distinguish between a match, a different pair, or a read error without connecting to the server.

In this article
Если отдельный файл id_ed25519.pub должен соответствовать приватному ключу id_ed25519, сначала локально извлеките открытую часть командой ssh-keygen -y. Затем вычислите для извлечённого и полученного публичных ключей отпечатки с явным -E sha256 и сравните значения целиком. Совпали — оба файла описывают одну пару. Различаются или приватный ключ не читается — не меняйте authorized_keys до выяснения причины.
Совпадение отвечает только на вопрос о паре. Оно не доказывает, что публичный ключ уже установлен на нужном сервере, что его принимает действующая конфигурация SSH, что приватный ключ никому больше не доступен или что у администратора сохранён запасной путь входа.
Входные условия и границы проверки
Linux или другая система с OpenSSH и утилитой
ssh-keygen.Приватный ключ в файловом формате OpenSSH, который
ssh-keygenумеет прочитать, и отдельный публичный ключ.Локальный каталог с правами только для владельца. Подключение к серверу и права
rootдля этой проверки не нужны.Ключи на аппаратном токене, в агенте,
PKCS#11илиFIDOбез доступного файла требуют процедуры своего провайдера; показанный файловый сценарий к ним не переносится автоматически.
Проверка выполнена 19 ноября 2026 года на OpenSSH_10.0p2 Debian-7+deb13u4 с OpenSSL 3.5.7. Учебный сценарий дважды создал две независимые пары Ed25519 без парольной фразы, подтвердил совпадающую пару, обнаружил другую пару и отказался читать усечённую копию приватного ключа. Рабочий сервер, сеть и authorized_keys не изменялись.
Почему комментарий и имя файла ничего не доказывают
Публичный ключ OpenSSH состоит из типа, закодированного ключевого материала и необязательного комментария. Комментарии вроде admin@server можно повторить у разных ключей, а файлы можно переименовать. Поэтому сравнивать нужно ключевой материал, а не комментарий после него и не имя файла.
Документация по ssh-keygen(1) описывает параметр -y как чтение приватного ключа OpenSSH и вывод соответствующего публичного ключа. Параметр -l показывает отпечаток, а -E sha256 явно выбирает SHA-256. Явный алгоритм полезен для воспроизводимого отчёта: без него сравнение может зависеть от настроек или старых инструкций с MD5.
Сначала проверим в изолированном окружении
Всё окружение запускается одним фрагментом в подоболочке. Защита включается до создания временного каталога; путь сразу проверяется, а trap при любом выходе удаляет только каталог, чей путь соответствует ожидаемому шаблону. Сеть, сервер и пользовательские ключи этот сценарий не затрагивает.
(
set -euo pipefail
umask 077
lab_dir="$(mktemp -d "${TMPDIR:-/tmp}/ssh-key-pair-lab.XXXXXX")"
case "$lab_dir" in
"${TMPDIR:-/tmp}"/ssh-key-pair-lab.*) ;;
*) printf 'unexpected lab path: %s\n' "$lab_dir" >&2; exit 90 ;;
esac
trap 'rm -rf -- "$lab_dir"' EXIT
chmod 700 "$lab_dir"
ssh-keygen -q -t ed25519 -N '' -C 'lab-key-a' -f "$lab_dir/key_a"
ssh-keygen -q -t ed25519 -N '' -C 'lab-key-b' -f "$lab_dir/key_b"
ssh-keygen -y -f "$lab_dir/key_a" > "$lab_dir/derived_a.pub"
[[ -s "$lab_dir/derived_a.pub" ]]
derived_fp="$(ssh-keygen -lf "$lab_dir/derived_a.pub" -E sha256 | awk '{print $2}')"
stored_a_fp="$(ssh-keygen -lf "$lab_dir/key_a.pub" -E sha256 | awk '{print $2}')"
stored_b_fp="$(ssh-keygen -lf "$lab_dir/key_b.pub" -E sha256 | awk '{print $2}')"
if [[ "$derived_fp" == "$stored_a_fp" ]]; then pair_a_rc=0; else pair_a_rc=1; fi
if [[ "$derived_fp" == "$stored_b_fp" ]]; then pair_b_rc=0; else pair_b_rc=1; fi
printf 'pair_a_rc=%s\npair_b_rc=%s\n' "$pair_a_rc" "$pair_b_rc"
cp -- "$lab_dir/key_a" "$lab_dir/broken_key"
truncate -s 80 "$lab_dir/broken_key"
broken_rc=0
ssh-keygen -y -f "$lab_dir/broken_key" > "$lab_dir/broken.pub" || broken_rc=$?
printf 'broken_rc=%s\n' "$broken_rc"
[[ "$broken_rc" -ne 0 ]]
[[ ! -s "$lab_dir/broken.pub" ]]
)
Сравнение | Наблюдение в двух запусках | Вывод |
|---|---|---|
|
| Один и тот же публичный ключ |
|
| Другая пара |
Одинаковые комментарии или имена | Не использовались как признак | Не являются доказательством пары |
Сами отпечатки SHA-256 в двух запусках различались, потому что пары создавались заново. Внутри каждого запуска отпечаток извлечённого A точно совпал с публичным A и отличался от публичного B. Это и есть проверяемое отношение; копировать конкретный хеш из учебного вывода не нужно.

Ошибка чтения — отдельный результат, а не «другая пара»
Для третьего сценария скрипт усекал до 80 байт только копию приватного ключа. В двух запусках ssh-keygen завершился с кодом 255, а broken.pub остался пустым. Это ошибка чтения, а не несовпадение пары: сначала подтверждают успешное извлечение, затем вычисляют отпечатки. trap очистил проверенный временный каталог и при штатном, и при ошибочном результате.
Как проверить свои два файла
Сделайте копию публичного файла, который собираетесь установить. Приватный ключ не копируйте в общий каталог и не отправляйте в журнал.
Извлеките открытую часть приватного ключа в защищённый временный файл. Требуйте код 0.
Получите отпечатки SHA-256 извлечённого и предоставленного публичных ключей.
Сравните строки целиком. При различии остановите изменение доступа и выясните происхождение файлов.
После совпадения отдельно проверьте строку для
authorized_keys, параметры, с которыми сейчас работает службаsshd, и запасной доступ через уже открытую сессию или консоль провайдера.
(
set -euo pipefail
umask 077
tmp_pub="$(mktemp "${TMPDIR:-/tmp}/derived-ssh-key.XXXXXX.pub")"
trap 'rm -f -- "$tmp_pub"' EXIT
ssh-keygen -y -f ./id_ed25519 > "$tmp_pub"
[[ -s "$tmp_pub" ]]
derived_fp="$(ssh-keygen -lf "$tmp_pub" -E sha256 | awk '{print $2}')"
supplied_fp="$(ssh-keygen -lf ./id_ed25519.pub -E sha256 | awk '{print $2}')"
if [[ "$derived_fp" == "$supplied_fp" ]]; then
printf 'MATCH %s\n' "$derived_fp"
else
printf 'MISMATCH derived=%s supplied=%s\n' "$derived_fp" "$supplied_fp"
exit 1
fi
)
Пути ./id_ed25519 и ./id_ed25519.pub — заглушки: замените их проверенными путями. Если приватный ключ защищён парольной фразой, ssh-keygen может запросить её интерактивно. Не добавляйте парольную фразу в командную строку, сценарий или журнал ради автоматизации этой проверки.
Что остаётся проверить после совпадения
Публичный ключ действительно добавлен в учётную запись нужного пользователя, а не только лежит в локальном файле.
Права каталога
.sshи файлаauthorized_keysдопускаются сервером; параметрыMatch,AuthorizedKeysFileиAuthenticationMethodsне направляют проверку в другое место.Приватный ключ защищён, имеет понятного владельца и не был скопирован посторонним. Совпадение пары не показывает историю доступа к файлу.
Новая сессия открывается ожидаемым способом, а текущая сессия или консоль провайдера остаётся доступна до завершения проверки.
Автоматизация, резервное копирование и развёртывание используют именно тот ключ и не зависят от старого файла.
Для следующего этапа используйте отдельную проверку эффективных настроек SSH для конкретного пользователя. Локальная пара и серверное решение о допуске — разные слои.
Критерии приёмки
Проверка | Ожидаемый результат | Если не выполнено |
|---|---|---|
| Код 0 и непустой публичный ключ | Остановиться; проверить путь, формат, права и парольную фразу |
Два отпечатка вычислены с | Обе команды завершились успешно | Не сравнивать частичный или пустой вывод |
Отпечатки совпали | Пара подтверждена локально | Не менять |
Новая SSH-сессия проверена после изменения | Вход работает нужным пользователем и ключом | Сохранить текущий доступ и вернуть согласованное состояние |
Запасной путь доступа сохранён | Есть действующая сессия или проверенная консоль | Не закрывать единственный рабочий канал |
По одному признаку выводить рано. Совпавший комментарий, знакомое имя файла или успешное чтение обоих ключей не подтверждают пару. Доказательство здесь состоит из успешного извлечения, двух отпечатков одного алгоритма и их точного совпадения; серверный доступ проверяется отдельно.
If a separate file id_ed25519.pub must correspond to the private key id_ed25519, first locally extract the public part using the ssh-keygen -y command. Then compute fingerprints for the extracted and received public keys using explicit -E sha256 and compare the full values. If they match, both files describe the same pair. If they differ or the private key cannot be read, do not modify authorized_keys until the cause is determined.
A match answers only whether the keys form a pair. It does not prove that the public key is already installed on the target server, that the active SSH configuration accepts it, that the private key is not accessible to anyone else, or that the administrator has a backup login path.
Input Conditions and Verification Boundaries
Linux or another system with OpenSSH and the
ssh-keygenutility.A private key in OpenSSH file format that
ssh-keygencan read, and a separate public key.A local directory with owner-only permissions. Connecting to the server and
rootpermissions are not required for this check.Keys on a hardware token, in an agent,
PKCS#11, orFIDOwithout an accessible file require their provider's procedure; the shown file-based scenario does not automatically apply to them.
The check was performed on November 19, 2026, on OpenSSH_10.0p2 Debian-7+deb13u4 with OpenSSL 3.5.7. The tutorial scenario twice generated two independent Ed25519 key pairs without a passphrase, confirmed a matching pair, detected a different pair, and refused to read a truncated copy of the private key. The production server, network, and authorized_keys remained unchanged.
Why Comments and Filenames Prove Nothing
An OpenSSH public key consists of a type, encoded key material, and an optional comment. Comments like admin@server can be repeated across different keys, and files can be renamed. Therefore, compare the key material, not the comment following it or the filename.
Documentation for ssh-keygen(1) describes the parameter -y as reading an OpenSSH private key and outputting the corresponding public key. The parameter -l displays the fingerprint, while -E sha256 explicitly selects SHA-256. Specifying the algorithm explicitly is useful for reproducible reports: without it, comparisons may depend on settings or outdated instructions using MD5.
First, Verify in an Isolated Environment
The entire environment runs as a single snippet within a subshell. Protection is enabled before the temporary directory is created; the path is checked immediately, and a trap on any exit removes only the directory whose path matches the expected pattern. This scenario does not involve the network, server, or user keys.
(
set -euo pipefail
umask 077
lab_dir="$(mktemp -d "${TMPDIR:-/tmp}/ssh-key-pair-lab.XXXXXX")"
case "$lab_dir" in
"${TMPDIR:-/tmp}"/ssh-key-pair-lab.*) ;;
*) printf 'unexpected lab path: %s\n' "$lab_dir" >&2; exit 90 ;;
esac
trap 'rm -rf -- "$lab_dir"' EXIT
chmod 700 "$lab_dir"
ssh-keygen -q -t ed25519 -N '' -C 'lab-key-a' -f "$lab_dir/key_a"
ssh-keygen -q -t ed25519 -N '' -C 'lab-key-b' -f "$lab_dir/key_b"
ssh-keygen -y -f "$lab_dir/key_a" > "$lab_dir/derived_a.pub"
[[ -s "$lab_dir/derived_a.pub" ]]
derived_fp="$(ssh-keygen -lf "$lab_dir/derived_a.pub" -E sha256 | awk '{print $2}')"
stored_a_fp="$(ssh-keygen -lf "$lab_dir/key_a.pub" -E sha256 | awk '{print $2}')"
stored_b_fp="$(ssh-keygen -lf "$lab_dir/key_b.pub" -E sha256 | awk '{print $2}')"
if [[ "$derived_fp" == "$stored_a_fp" ]]; then pair_a_rc=0; else pair_a_rc=1; fi
if [[ "$derived_fp" == "$stored_b_fp" ]]; then pair_b_rc=0; else pair_b_rc=1; fi
printf 'pair_a_rc=%s\npair_b_rc=%s\n' "$pair_a_rc" "$pair_b_rc"
cp -- "$lab_dir/key_a" "$lab_dir/broken_key"
truncate -s 80 "$lab_dir/broken_key"
broken_rc=0
ssh-keygen -y -f "$lab_dir/broken_key" > "$lab_dir/broken.pub" || broken_rc=$?
printf 'broken_rc=%s\n' "$broken_rc"
[[ "$broken_rc" -ne 0 ]]
[[ ! -s "$lab_dir/broken.pub" ]]
)
Comparison | Observation from two runs | Output |
|---|---|---|
|
| The same public key |
|
| A different pair |
Identical comments or names | Not used as an indicator | Do not constitute proof of a pair |
The SHA-256 fingerprints differed between the two runs because the pairs were regenerated. Within each run, the fingerprint of the extracted A matched the public A exactly and differed from the public B. This is the verifiable relationship; there is no need to copy a specific hash from the training output.

A read error is a distinct result, not a "different pair"
For the third scenario, the script truncated only the private key copy to 80 bytes. In two runs, ssh-keygen exited with code 255, while broken.pub remained empty. This is a read error, not a pair mismatch: first confirm successful extraction, then compute the fingerprints. trap cleared the verified temporary directory for both normal and error results.
How to verify your two files
Make a copy of the public file you intend to install. Do not copy the private key to a shared directory or send it to the log.
Extract the public part of the private key into a secure temporary file. Require exit code 0.
Obtain the SHA-256 fingerprints of the extracted and provided public keys.
Compare the lines in their entirety. If they differ, halt access changes and determine the origin of the files.
After confirming a match, separately verify the line for
authorized_keys, the parameters currently used by thesshdservice, and the backup access via the already open session or provider console.
(
set -euo pipefail
umask 077
tmp_pub="$(mktemp "${TMPDIR:-/tmp}/derived-ssh-key.XXXXXX.pub")"
trap 'rm -f -- "$tmp_pub"' EXIT
ssh-keygen -y -f ./id_ed25519 > "$tmp_pub"
[[ -s "$tmp_pub" ]]
derived_fp="$(ssh-keygen -lf "$tmp_pub" -E sha256 | awk '{print $2}')"
supplied_fp="$(ssh-keygen -lf ./id_ed25519.pub -E sha256 | awk '{print $2}')"
if [[ "$derived_fp" == "$supplied_fp" ]]; then
printf 'MATCH %s\n' "$derived_fp"
else
printf 'MISMATCH derived=%s supplied=%s\n' "$derived_fp" "$supplied_fp"
exit 1
fi
)
The paths ./id_ed25519 and ./id_ed25519.pub are placeholders: replace them with verified paths. If the private key is protected by a passphrase, ssh-keygen may prompt for it interactively. Do not add the passphrase to the command line, script, or log to automate this check.
What remains to check after a match
The public key is indeed added to the target user's account, not just present in a local file.
The permissions for directory
.sshand fileauthorized_keysare acceptable to the server; parametersMatch,AuthorizedKeysFile, andAuthenticationMethodsdo not redirect the check elsewhere.The private key is protected, has a clear owner, and has not been copied by an unauthorized party. A key pair match does not reveal the file access history.
A new session opens as expected, while the current session or provider console remains accessible until the verification completes.
Automation, backup, and deployment use exactly that key and do not depend on the old file.
For the next stage, use a separate check of effective SSH settings for the specific user. The local pair and the server-side access decision are different layers.
Acceptance criteria
Verification | Expected result | If not met |
|---|---|---|
| Exit code 0 and a non-empty public key | Stop; verify path, format, permissions, and passphrase |
Two fingerprints computed with | Both commands completed successfully | Do not compare partial or empty output |
Fingerprints match | Pair confirmed locally | Do not change |
New SSH session verified after the change | Login works with the correct user and key | Preserve current access and restore a consistent state |
Backup access path is saved | An active session or verified console exists | Do not close the only working channel |
It is premature to conclude based on a single sign. A matching comment, a familiar filename, or successful reading of both keys does not confirm the pair. Proof here consists of successful extraction, two fingerprints from the same algorithm, and their exact match; server access is verified separately.





Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.