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)
13331정성태4/27/20233885오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233529Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233732Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233401VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233808VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235231.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234525스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234356.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234287개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235063VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233890개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233870개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234318개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234150개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234237오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233565오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233775Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233859개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233937개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233951Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234462C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234060C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234228.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234122스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233886.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233675Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...