C# - ssh-ed25519 유형의 Public Key 파일 해석
SSH 서버의 경우 /etc/ssh 경로에 ssh_host_*_key.pub와 같은 유형의 공개키 파일이 존재하고, 그중 하나가 (제약이 유독 심한) ssh_host_ed25519_key.pub 파일입니다.
# cat /etc/ssh/ssh_host_ed25519_key.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF18y7iEZwsx99NueMWE+tTVdhaDLfudFYU4fonJHbYs root@6747bfaa58b8
# ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
256 SHA256:x9Y3qATAqJjoaOUnV8eqj5SLZ9fnoqJd7Nz5VsT7Dbo root@6747bfaa58b8 (ED25519)
// -l: [-v] [-E fingerprint_hash] [-f input_keyfile]
그런데,
pscp와 같은 프로그램에서는 SshHostKeyFingerprint의 유형을 MD5 형식의 포맷으로 지정해야 하는데요,
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:..." // 이 값이 md5 형식
};
이것을 알아내는 방법은 여러 가지가 있겠지만, 제 경우에는 그냥 아무 디렉터리나 pscp로 복사 시도를 해보는 것입니다.
c:\temp> pscp -P 23022 -v -r c:\temp\empty root@192.168.100.50:/home/root/test
Connecting to 192.168.100.50 port 23022
We claim version: SSH-2.0-PuTTY_Release_0.70
Server version: SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.7
Using SSH protocol version 2
Doing ECDH key exchange with curve Curve25519 and hash SHA-256
Server also has ecdsa-sha2-nistp256/ssh-rsa host keys, but we don't know any of them
Host key fingerprint is:
ssh-ed25519 256 b4:7f:29:5c:fd:e1:ea:f5:7d:6d:73:df:01:79:cf:2c
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's ssh-ed25519 key fingerprint is:
ssh-ed25519 256 b4:7f:29:5c:fd:e1:ea:f5:7d:6d:73:df:01:79:cf:2c
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
그럼, 실행 결과에 저렇게 md5 형식의 fingerprint 값이 출력되므로 그대로 사용하면 됩니다. 또 다른 방법으론 ssh-keygen 명령어를 사용할 수 있습니다.
get SSH key fingerprint in (old) hex format on new version of openssh
; https://superuser.com/questions/1088165/get-ssh-key-fingerprint-in-old-hex-format-on-new-version-of-openssh
// ssh 서버가 설치된 서버에서, 또는 public key 파일만 구할 수 있다면!
# ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_ed25519_key.pub
256 MD5:b4:7f:29:5c:fd:e1:ea:f5:7d:6d:73:df:01:79:cf:2c root@6747bfaa58b8 (ED25519)
그나저나, 이걸 코드로도 알아낼 수 있겠죠? ^^ 방법은 매우 간단한데요, 저 md5 해시값은 단순히 ssh_host_ed25519_key.pub의 키 정보를 나타내는 텍스트로부터 구한 것입니다. 즉, "AAAAC3NzaC1lZDI1NTE5AAAAIF18y7iEZwsx99NueMWE+tTVdhaDLfudFYU4fonJHbYs" 문자열을 base64 디코딩한 후, 그걸 그대로 MD5 해시로 변환하면 됩니다.
// ssh_host_ed25519_key.pub 파일의 내용 중 공개키 정보 문자열
string text = "AAAAC3NzaC1lZDI1NTE5AAAAIF18y7iEZwsx99NueMWE+tTVdhaDLfudFYU4fonJHbYs";
// base64 decode
byte[] data = Convert.FromBase64String(text);
byte[] buffer = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(buffer).Replace("-", ":"));
/* 출력 결과
B4:7F:29:5C:FD:E1:EA:F5:7D:6D:73:DF:01:79:CF:2C
*/
마침 지난 경험도 있고 하니,
C# - ssh-keygen으로 생성한 Public Key 파일 해석과 fingerprint 값(md5, sha256) 생성
; https://www.sysnet.pe.kr/2/0/13739
기왕 하는 김에 ssh_host_ed25519_key.pub 파일의 내용도 해석해 보겠습니다. 결국 이것도 ANS.1 인코딩 방식일 거라는 추측을 할 수 있는데요,
# cat /etc/ssh/ssh_host_ed25519_key.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF18y7iEZwsx99NueMWE+tTVdhaDLfudFYU4fonJHbYs root@6747bfaa58b8
[The key type] [A chunk of PEM-encoded data] [A comment]
예)ssh-ed25519 AAA...[생략]...onHbYs root@6747bfaa58b8
// ssh-rsa 형식인 경우의 해석은 "https://www.sysnet.pe.kr/2/0/13739#rfc4253" 참조.
따라서 "AAAAC3NzaC1lZDI1NTE5AAAAIF18y7iEZwsx99NueMWE+tTVdhaDLfudFYU4fonJHbYs" 문자열을, 즉 "[A chunk of PEM-encoded data]" 영역을 base64 디코딩하면 다음과 같은 정보를 담은 바이트 배열이 나옵니다.
[4바이트 길이(big endian)] [algorithm name, ("ssh-ed25519")]
[4바이트 길이(big endian)] [public key (ASN.1)]
코딩으로 구현하면 이렇고!
string text = "AAAAC3NzaC1lZDI1NTE5AAAAIF18y7iEZwsx99NueMWE+tTVdhaDLfudFYU4fonJHbYs";
byte[] data = Convert.FromBase64String(text);
(string algorithmName, byte[] publicKey) = DecodeSSHED25519PublicKey(data);
private static (string algorithmName, byte[] publicKey) DecodeSSHED25519PublicKey(byte[] bytesEncoded)
{
string algorithmName;
byte[] publicKey;
using (var stream = new MemoryStream(bytesEncoded))
using (var reader = new BinaryReader(stream))
{
int algorithmLength = reader.ReadInt32BE();
algorithmName = Encoding.ASCII.GetString(reader.ReadBytes(algorithmLength));
int publicKeyLength = reader.ReadInt32BE();
publicKey = reader.ReadBytes(publicKeyLength);
}
return (algorithmName, publicKey);
}
사실 저 코드를 직접 만들 필요는 없는데요, 이미 예전 글에서
SSH.NET 라이브러리에서 제공하는 PublicKeyFile 클래스로 다룬 적이 있었습니다.
C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동
; https://www.sysnet.pe.kr/2/0/13749#enc_dec_src
저 예제 코드의 "PublicKeyFile.DecodeEdDSA" 메서드가 했던 작업이 바로 위에서 살펴본 DecodeSSHED25519PublicKey 메서드입니다. 따라서 (이젠 DecodeEdDSA 메서드 대신) 다음과 같이 우리가 구한 공개키로 Ed25519Signer를 초기화할 수 있습니다.
(string algorithmName, byte[] publicKey) = DecodeSSHED25519PublicKey(data);
Console.WriteLine(algorithmName); // 출력 결과: "ssh-ed25519"
Ed25519PublicKeyParameters publicKeyParam = new Ed25519PublicKeyParameters(publicKey);
Ed25519Signer signer = new Ed25519Signer();
signer.Init(false, publicKeyParam);
// ... 개인키로 서명한 데이터 검증...
/*
signer.BlockUpdate(plainTextBuffer);
bool verified = signer.VerifySignature(signedBuffer);
*/
(
첨부 파일은 이 글의 예제 코드를 포함합니다.)
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]