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)
13549정성태2/3/20242473개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242306개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242054개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241894Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241826닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241822Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241875오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241920VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242050Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242143개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242212닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242259닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242371닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242200닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242030닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242223닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242134닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242019닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242009닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241893닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242030Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241957오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242045닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242011오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242063오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...