Microsoft MVP성태의 닷넷 이야기
닷넷: 2372. C# - ssh-ed25519 유형의 Public Key 파일 해석 [링크 복사], [링크+제목 복사],
조회: 785
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 15개 있습니다.)
.NET Framework: 292. RSACryptoServiceProvider의 공개키와 개인키 구분
; https://www.sysnet.pe.kr/2/0/1218

.NET Framework: 327. RSAParameters와 System.Numerics.BigInteger 이야기
; https://www.sysnet.pe.kr/2/0/1295

.NET Framework: 329. C# - Rabin-Miller 소수 생성방법을 이용하여 RSACryptoServiceProvider의 개인키를 직접 채워보자
; https://www.sysnet.pe.kr/2/0/1300

.NET Framework: 356. (공개키를 담은) 자바의 key 파일을 닷넷의 RSACryptoServiceProvider에서 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1401

.NET Framework: 383. RSAParameters의 ToXmlString과 ExportParameters의 결과 비교
; https://www.sysnet.pe.kr/2/0/1491

.NET Framework: 565. C# - Rabin-Miller 소수 생성 방법을 이용하여 RSACryptoServiceProvider의 개인키를 직접 채워보자 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/10925

.NET Framework: 566. openssl의 PKCS#1 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법
; https://www.sysnet.pe.kr/2/0/10926

.NET Framework: 638. RSAParameters와 RSA
; https://www.sysnet.pe.kr/2/0/11140

.NET Framework: 1037. openssl의 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 (2)
; https://www.sysnet.pe.kr/2/0/12598

.NET Framework: 2093. C# - PKCS#8 PEM 파일을 이용한 RSA 개인키/공개키 설정 방법
; https://www.sysnet.pe.kr/2/0/13245

닷넷: 2297. C# - ssh-keygen으로 생성한 Public Key 파일 해석과 fingerprint 값(md5, sha256) 생성
; https://www.sysnet.pe.kr/2/0/13739

닷넷: 2297. C# - ssh-keygen으로 생성한 ecdsa 유형의 Public Key 파일 해석
; https://www.sysnet.pe.kr/2/0/13742

닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷
; https://www.sysnet.pe.kr/2/0/13747

닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동
; https://www.sysnet.pe.kr/2/0/13749

닷넷: 2372. C# - ssh-ed25519 유형의 Public Key 파일 해석
; https://www.sysnet.pe.kr/2/0/14029




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);
*/

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/17/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13855정성태12/28/202410317오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20249885C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20248001디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/202410961디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20248398디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/202410747오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/202410382디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20249601디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20249099오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/202410956디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20247975디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/202411562디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20248703오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20249340디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/202410005오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20249074오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/202410473오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/202410266오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/202411177디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20248261디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/202410903오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/202410954Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/202410053개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20249862Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20248723Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/202411718개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...