Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 10개 있습니다.)
.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의 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# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법
; https://www.sysnet.pe.kr/2/0/13245




(공개키를 담은) 자바의 key 파일을 닷넷의 RSACryptoServiceProvider에서 사용하는 방법


이 글은 아래의 질문에 대한 답변을 정리한 것입니다.

안녕하세요. RSA공개키 알고리즘에 나와있는 글을 보고 응용을 해야 하는데 막히는 부분이 있어서 질문드립니다.
; https://www.sysnet.pe.kr/3/0/1107

이야기인 즉, 자바 측 개발자로부터 "[publickey].key" 파일을 받았는데 이것을 닷넷의 RSA 키로 가져올 수 없다는 것입니다.

예전에 자바 키 파일을 다뤄본 적이 있었는데요. ^^

.keystore 파일에 저장된 개인키 추출방법과 인증기관으로부터 온 공개키를 합친 pfx 파일 만드는 방법
; https://www.sysnet.pe.kr/2/0/1262

위의 글에 나온 key 파일은 개인키를 담고 있는 유형이었는데, 지금 상황에 있는 key 파일은 공개키만 가진 것입니다. 따라서 pvk.exe를 이용하여 개인키를 가진 PEM(Privacy Enhanced Email) 파일로의 변환은 맞지 않습니다.

그러게요... key 파일만 달랑 주면 어떡합니까? ^^; 그 키 파일의 포맷을 알려줘야 변환해서 쓰든가 하죠.

X509EncodedKeySpec으로 웹 검색을 해보니, 이것이 일반 X.509 표준키 포맷의 ASN.1 인코딩 표현임을 알게 되었습니다.

What Is Key Encoding?
; http://www.herongyang.com/Cryptography/JCE-Key-Encoding-What-Is-Key-Encoding.html

* PKCS#8 - PKCS stands for Public-Key Cryptography Standards, developed by RSA Security currently a division of EMC. PKCS#8 describes syntax for private-key information, including a private key for some public-key algorithm and a set of attributes. PKCS#8 is mainly used to encode private keys.

* X.509 - X.509 is an ITU-T standard for a public key infrastructure (PKI) for single sign-on and Privilege Management Infrastructure (PMI). X.509 specifies, amongst other things, standard formats for public key certificates, certificate revocation lists, attribute certificates, and a certification path validation algorithm.

* PKCS8EncodedKeySpec - A sub class of EncodedKeySpec represents the ASN.1 encoding of a private key based on PKCS#8 standard.

* X509EncodedKeySpec - A sub class of EncodedKeySpec represents the ASN.1 encoding of a public key based on X.509 standard.


닷넷의 X509Certificate2 타입은 위에서 X.509 형식을 지원하는 것이지, 그것의 ANS.1 포맷을 지원하는 것은 아니기 때문에 로딩이 안되는 것입니다.

다행히 이 문제도 검색을 해보니 답이 나옵니다.

How to use key files in RSA Encryption using C#?
; http://stackoverflow.com/questions/6868867/how-to-use-key-files-in-rsa-encryption-using-c

BouncyCastle 라이브러리를 이용하라고 나오는데요.

자바 버전과 닷넷 버전이 함께 공개되어 있군요. ^^

The Legion of the Bouncy Castle
; http://www.bouncycastle.org

닷넷 버전의 Bouncy Castle
; http://www.bouncycastle.org/csharp/

다운로드 받은 후, 압축을 해제하면 BouncyCastle.Crypto.dll 파일 하나만 나옵니다. (편해서 좋군요. ^^) 그 파일을 참조해서 Org.BouncyCastle.Security.PublicKeyFactory.CreateKey를 이용하여 공개키(.key)파일을 로드하면 됩니다.

string filePath = ...[.key파일 경로]...;
byte[] pubKeys = File.ReadAllBytes(filePath);

Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters pubKey = Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(pubKeys)
    as Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters;

System.Security.Cryptography.RSAParameters rsaParam = new System.Security.Cryptography.RSAParameters();
rsaParam.Exponent = pubKey.Exponent.ToByteArray();
rsaParam.Modulus = pubKey.Modulus.ToByteArray();

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParam);

Console.WriteLine(pubKey);

첨부한 파일은 위의 코드를 담은 간략한 테스트 프로젝트입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/14/2021]

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

비밀번호

댓글 작성자
 



2013-01-15 08시28분
[윤용한] java의 public key bytes를 사용하는 또 다른 방법입니다.

MatiPublicKey 는 다음과 같이 DER encoding 되어 있습니다.

        Offset| Len |LenByte|
        ======+======+=======+======================================================================
             0| 159| 2| SEQUENCE :
             3| 13| 1| SEQUENCE :
             5| 9| 1| OBJECT IDENTIFIER : rsaEncryption [1.2.840.113549.1.1.1]
            16| 0| 1| NULL :
            18| 141| 2| BIT STRING UnusedBits:0 :
            22| 137| 2| SEQUENCE :
            25| 129| 2| INTEGER :
              | | | 00B2BA169C3405FF128BD171CE37121A6AF46E080293B496
              | | | E93F44ECEE0BC59AC127894D6989B4DD4813478E39D08C03
              | | | B8322A31DCA6145AED376F01E92CE4DB386B771C8945CEB9
              | | | A1CEF44FBAC653D056EAD30F03CC6E10E6CFDC11234BD171
              | | | F743E613A46D88F2E547372D1DEDDE8E9AFE1F0C48474086
              | | | B8FB9F2A48F3467E5B
           157| 3| 1| INTEGER : 65537

이걸 RSAParameters로 로드 하기 위해서 필요한 부분은 마지막에 있는 두 INTEGER 파트(Modulus와 Exponent)입니다.
따라서 간단하게 전용 DER parser를 만들어서 사용하면 될 거 같네요.
이걸 사용하여 public key를 로드 하고 aes 암호화 까지 진행하는 샘플코드를 만듭니다.

        private static byte[] MatiPublicKeyBytes = Convert.FromBase64String(
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyuhacNAX/EovRcc43Ehpq9G4IApO0luk/ROzuC8WawSeJTWmJtN1IE0eOOdCMA7gyKjHcphRa7TdvAeks5Ns4a3cciUXOuaHO9E+6xlPQVurTDwPMbhDmz9wRI0vRcfdD5hOkbYjy5Uc3LR3t3o6a/h8MSEdAhrj7nypI80Z+WwIDAQAB");

        static void Main(string[] args)
        {
            byte[] encryptedMessage;
            byte[] encryptedSessionKey;
            string secretMessage = "value4";

            using (var rsa = new RSACryptoServiceProvider())
            {
                var pubKey = RSAParametersUtil.FromPublicKeyBytes(MatiPublicKeyBytes);
                rsa.ImportParameters(pubKey);

                Console.WriteLine(pubKey);
                Console.WriteLine(Convert.ToBase64String(rsa.ExportCspBlob(false)));

                using (Aes aes = new AesCryptoServiceProvider())
                {
                    var keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsa);
                    encryptedSessionKey = keyFormatter.CreateKeyExchange(aes.Key, typeof(Aes));

                    using (var ciphertext = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            var plaintextMessage = Encoding.UTF8.GetBytes(secretMessage);
                            cryptoStream.Write(plaintextMessage, 0, plaintextMessage.Length);
                            cryptoStream.Close();
                            encryptedMessage = ciphertext.ToArray();

                            Console.WriteLine("send: {0}", Convert.ToBase64String(encryptedMessage));
                        }
                    }
                    Console.WriteLine("encryptedSessionKey: {0}", Convert.ToBase64String(encryptedSessionKey));
                }
            }
        }



file: RSAParamsUtil.cs

    using System;
    using System.Security.Cryptography;

    /// <summary>
    /// java의 PublicKeyBytes만 파싱한다!!
    /// yonghan@gmail.com
    /// </summary>
    public static class RSAParametersUtil
    {
        /* sample public key bytes
        Offset| Len |LenByte|
        ======+======+=======+======================================================================
             0| 159| 2| SEQUENCE :
             3| 13| 1| SEQUENCE :
             5| 9| 1| OBJECT IDENTIFIER : rsaEncryption [1.2.840.113549.1.1.1]
            16| 0| 1| NULL :
            18| 141| 2| BIT STRING UnusedBits:0 :
            22| 137| 2| SEQUENCE :
            25| 129| 2| INTEGER :
              | | | 00B2BA169C3405FF128BD171CE37121A6AF46E080293B496
              | | | E93F44ECEE0BC59AC127894D6989B4DD4813478E39D08C03
              | | | B8322A31DCA6145AED376F01E92CE4DB386B771C8945CEB9
              | | | A1CEF44FBAC653D056EAD30F03CC6E10E6CFDC11234BD171
              | | | F743E613A46D88F2E547372D1DEDDE8E9AFE1F0C48474086
              | | | B8FB9F2A48F3467E5B
           157| 3| 1| INTEGER : 65537
        */
        /// <summary>
        /// java에서 생성된 PublicKeyBytes만 파싱한다!!
        /// </summary>
        /// <param name="publicKeyBytes"></param>
        public static RSAParameters FromPublicKeyBytes(byte[] publicKeyBytes)
        {
            var offset = 0;
            byte[] modulus = null;
            byte[] exponent = null;
            do
            {
                byte tag = publicKeyBytes[offset++];
                int length;
                if (tag == 0x30 /*SEQUENCE*/)
                {
                    length = DecodeLength(publicKeyBytes, ref offset);
                    //Console.WriteLine("SEQUENCE length={0}", length);
                }
                else if (tag == 0x02 /*INTEGER*/)
                {
                    length = DecodeLength(publicKeyBytes, ref offset);
                    var value = new byte[length];
                    Buffer.BlockCopy(publicKeyBytes, offset, value, 0, length);
                    offset += length;
                    // modulus와 exponent는 순차적으로 나타난다.
                    if (modulus == null) modulus = value;
                    else if (exponent == null) exponent = value;
                    //Console.WriteLine("INTEGER length={0}, {1}", length, BitConverter.ToString(value));
                }
                else if (tag == 0x03 /*BIT STRING*/)
                {
                    length = DecodeLength(publicKeyBytes, ref offset);
                    int unusedBits = publicKeyBytes[offset++];
                    //Console.WriteLine("BIT STRING length={0}, UnusedBits={1}", length, unusedBits);
                }
                else if (tag == 0x04 /*OCTET STRING*/)
                {
                    length = DecodeLength(publicKeyBytes, ref offset);
                    var value = new byte[length];
                    Buffer.BlockCopy(publicKeyBytes, offset, value, 0, length);
                    offset += length;
                    //Console.WriteLine("OCTET STRING length={0}, {1}", length, BitConverter.ToString(value));
                }
                else if (tag == 0x05 /*NULL*/)
                {
                    length = publicKeyBytes[offset++];
                    offset += length;/*null value*/
                    //Console.WriteLine("NULL length={0}", length);
                }
                else if (tag == 0x06 /*OBJECT IDENTIFIER*/)
                {
                    length = publicKeyBytes[offset++];
                    var value = new byte[length];
                    Buffer.BlockCopy(publicKeyBytes, offset, value, 0, length);
                    offset += length;
                    //Console.WriteLine("OBJECT IDENTIFIER length={0}, {1}", length, BitConverter.ToString(value));
                }
            } while (offset < publicKeyBytes.Length);
            return new RSAParameters() { Modulus = modulus, Exponent = exponent };
        }

        internal static int DecodeLength(byte[] data, ref int offset)
        {
            int length = data[offset++];
            if ((length & 0x80) == 0x80)
            {
                // content length > 127
                var lol = length & ~0x80; // length of length, 첫번째 비트를 제거하여 length의 length를 구한다.
                length = 0;
                for (var t = 0; t < lol; t++)
                    length |= data[offset++] << ((lol - t - 1) * 8); // byte-order: big-endian (맞나???)
            }
            return length;
        }
    }
[guest]
2013-01-15 08시51분
윤용한 님 멋진 답변입니다 아예 자바의 파일 포맷을 알고 접근하시는군요. ^^
정성태

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232628닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232487닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232419닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232700Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232456닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232492개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232322개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232652닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232353Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232844닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232462닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232657닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232893닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232830닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232631스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232357스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232406오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232722스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232612닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232871닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232925닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233102닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233286스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233100닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233078스크립트: 58. 파이썬 - async/await 기본 사용법
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...