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)
13398정성태8/3/20234135스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233642닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233341스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233311개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233255오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233420닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233297오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233369닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233339스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233322개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233513오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233533오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233601Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20233820Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233566.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233313개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233356.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20233741오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233195스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233209스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233094오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20236895오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233283.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20232984스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233110오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234398오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...