Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 14개 있습니다.)
.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




C# - PKCS#8 PEM 파일을 이용한 RSA 개인키/공개키 설정 방법

예전에 쓴 글이,

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

C# - BouncyCastle을 사용한 암호화/복호화 예제
; https://www.sysnet.pe.kr/2/0/12992

이제는 openssl의 내용이 달라져서 헤매는 분들이 계시는군요. ^^ 이참에 업데이트 차원에서 글을 남깁니다.




openssl 도구를 이용하면 개인키를 담은 RSA PEM 파일을 다음과 같이 쉽게 생성할 수 있습니다.

c:\temp> openssl genrsa 2048
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC1IWcgsx34cMS8
K17VxHTQzpGRpIx4KTgrrJl2C14gh9PrbHCye9HipPwXhysLJ+PQLtWm9mx8jZC2
...[생략]...
Mon/3wDEyLMOftFNgaaAOOkMefhPABwQ1TG1lApa1mk3zGaTvbnksYbvHUohtedm
9MKZgdIakI4h9a74xwQv0+CE
-----END PRIVATE KEY-----

예전 글에서는 저 명령어의 결과로 "BEGIN RSA PRIVATE KEY" / "END RSA PRIVATE KEY" 쌍으로 나왔는데 이제는 "RSA"라는 문자열이 빠져 있습니다. 왜냐하면, 생성한 (base64 인코딩된) 데이터에 Key의 종류까지 포함하고 있기 때문입니다.

위와 같이 생성한 개인키는 이제 BouncyCastle을 이용해 다음과 같이 읽을 수 있습니다.

// Install-Package BouncyCastle.Cryptography

string privateKeyFilePath = "prvkey.pem";

Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(File.OpenText(privateKeyFilePath));
var key = pem.ReadObject() as Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters;

RSA는 서로의 키로 암호화한 데이터를 복호화하는 것이 가능합니다. 가령 개인키로 암호화하면 공개키로 복호화할 수 있고, 공개키로 암호화하면 개인키로 복호화할 수 있습니다. 하지만 키의 배포 측면에서 현실적인 이유로 인해, 보통은 공개키로 암호화하고 개인키로 복호화합니다. (아울러, 개인키로는 서명하고, 공개키로는 서명을 검증합니다.)

또한, 개인키 자체에는 공개키 데이터도 포함돼 있기 때문에 어찌 보면 위에서 구한 RsaPrivateCrtKeyParameters로 암호화를 하면 될 것도 같습니다.

string plainText = "Hello World";
byte[] encBuffer = EncryptData(key, plainText);

private static byte[] EncryptData(ICipherParameters keyParam, string data)
{
    var cipher = CipherUtilities.GetCipher("RSA/NONE/OAEPWITHSHA256ANDMGF1PADDING");
    cipher.Init(true, keyParam); // true == 암호화

    byte[] plain = Encoding.UTF8.GetBytes(data);
    return cipher.DoFinal(plain);
}

그런데, 저렇게 암호화한 데이터를 복호화하려고 하면,

Console.WriteLine(DecryptData(key, encBuffer));

private static string DecryptData(ICipherParameters keyParam, byte[] encrypted)
{
    var cipher = CipherUtilities.GetCipher("RSA/NONE/OAEPWITHSHA256ANDMGF1PADDING");
    cipher.Init(false, keyParam); // false == 복호화

    return Encoding.UTF8.GetString(cipher.DoFinal(encrypted));
}

"Org.BouncyCastle.Crypto.InvalidCipherTextException: data wrong" 예외가 발생합니다.

Unhandled exception. Org.BouncyCastle.Crypto.InvalidCipherTextException: data wrong
   at Org.BouncyCastle.Crypto.Encodings.OaepEncoding.DecodeBlock(Byte[] inBytes, Int32 inOff, Int32 inLen) in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\encodings\OaepEncoding.cs:line 272
   at Org.BouncyCastle.Crypto.Encodings.OaepEncoding.ProcessBlock(Byte[] inBytes, Int32 inOff, Int32 inLen) in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\encodings\OaepEncoding.cs:line 124
   at Org.BouncyCastle.Crypto.BufferedAsymmetricBlockCipher.DoFinal() in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\BufferedAsymmetricBlockCipher.cs:line 152
   at Org.BouncyCastle.Crypto.BufferedAsymmetricBlockCipher.DoFinal(Byte[] input, Int32 inOff, Int32 length) in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\BufferedAsymmetricBlockCipher.cs:line 167
   at Org.BouncyCastle.Crypto.BufferedCipherBase.DoFinal(Byte[] input)
   at ConsoleApp1.Program.DecryptData(ICipherParameters keyParam, Byte[] encrypted)
   at ConsoleApp1.Program.Main(String[] args)

아마도 키 자체가 RsaPrivateCrtKeyParameters 타입이기 때문에 암호화를 할 때 (공개키를 사용하지 않고) 개인키를 이용해 암호화를 한 것으로 보입니다. 그래서 복호화 할 때도 마찬가지로 개인키를 사용하기 때문에 "data wrong" 오류가 발생하는 것인데요, 실제로 이에 대한 확인을 복호화할 때 공개키를 명시적으로 지정해 보면 됩니다.

이를 위해 개인키로부터 공개키를 분리해 내고,

c:\temp> openssl rsa -pubout -in prvkey.pem -out pubkey.pem
writing RSA key

다음과 같이 테스트할 수 있습니다.

static void Main(string[] args)
{
    string privateKeyFilePath = "prvkey.pem";
    string publicKeyFilePath = "pubkey.pem";

    Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(File.OpenText(privateKeyFilePath));
    var key = pem.ReadObject() as Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters;
    if (key == null)
    {
        Console.WriteLine("Private Key is null");
        return;
    }

    string plainText = "Hello World";
    byte[] encBuffer = EncryptData(key, plainText);
    Console.WriteLine(Convert.ToBase64String(encBuffer));

    pem = new Org.BouncyCastle.OpenSsl.PemReader(File.OpenText(publicKeyFilePath));
    var pubkey = pem.ReadObject() as Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters;
    if (pubkey == null)
    {
        Console.WriteLine("Public Key is null");
        return;
    }
            
    Console.WriteLine(DecryptData(pubkey, encBuffer));
}

코드는 보는 바와 같이 개인키로 암호화가 된 것을 공개키로 복호화하기 때문에 잘 동작합니다. 물론, 원래대로 아래와 같이 공개키를 이용해 암호화하고 개인키를 이용해 복호화하도록 코딩해야 합니다.

static void Main(string[] args)
{
    string privateKeyFilePath = "prvkey.pem";
    string publicKeyFilePath = "pubkey.pem";

    Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(File.OpenText(publicKeyFilePath));
    var key = pem.ReadObject() as Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters;
    if (key == null)
    {
        Console.WriteLine("Public Key is null");
        return;
    }

    string plainText = "Hello World";
    byte[] encBuffer = EncryptData(key, plainText);
    Console.WriteLine(Convert.ToBase64String(encBuffer));

    pem = new Org.BouncyCastle.OpenSsl.PemReader(File.OpenText(privateKeyFilePath));
    var pubkey = pem.ReadObject() as Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters;
    if (pubkey == null)
    {
        Console.WriteLine("Private Key is null");
        return;
    }
            
    Console.WriteLine(DecryptData(pubkey, encBuffer));
}

참고로, 여전히 "RSA" 문자열이 있는 PKCS#1 포맷으로 생성하고 싶다면 -traditional 옵션을 적용하면 됩니다.

c:\temp> openssl genrsa -traditional 2048
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAv0t1fMeb6iIcgDAPXI/HD4XruSkCMAoNMSEGVN4OElF0oU4i
CIKpf91/ukoIC73AZwOFyx6gDTx6KErIYR1aN3JwcXkBTlk9r/K+8jME21c5SQXf
...[생략]...
ZsZ6SRYcsXZO9Lw08lnQuNbJaxYyVIORxZf/rzVmFuPiGTbjqwdD6FF5ks0zHYtI
5iClwv97z+UVmw/mzHkM0gqhinMYhHvY25Fr5i/hT9SNoLTwK4PO
-----END RSA PRIVATE KEY-----




그런데, 사실 이제 더 이상 BouncyCastle을 사용할 필요가 없습니다. 왜냐하면, .NET 5부터 PEM 파일에 대한 지원이 추가되었기 때문입니다.

How to read a PEM RSA private key from .NET
; https://stackoverflow.com/questions/243646/how-to-read-a-pem-rsa-private-key-from-net

그래서 다음과 같이 바로 처리할 수 있습니다.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

internal class Program
{
    static void Main(string[] args)
    {
        string privateKeyFilePath = "prvkey.pem";
        string publicKeyFilePath = "pubkey.pem";

        byte[] encBuffer = null;

        {
            var rsa = RSA.Create();
            string text = File.ReadAllText(publicKeyFilePath);
            rsa.ImportFromPem(text.ToCharArray());

            string plainText = "Hello World";
            byte[] buffer = Encoding.UTF8.GetBytes(plainText);
            encBuffer = rsa.Encrypt(buffer, RSAEncryptionPadding.OaepSHA256);
        }


        {
            var rsa = RSA.Create();
            string text = File.ReadAllText(privateKeyFilePath);
            rsa.ImportFromPem(text.ToCharArray());

            byte[] buffer = rsa.Decrypt(encBuffer, RSAEncryptionPadding.OaepSHA256);
            Console.WriteLine(Encoding.UTF8.GetString(buffer));
        }
    }
}

개인키/공개키 상관없이 일괄적으로 ImportFromPem 메서드를 호출하면 끝입니다. ^^

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/23/2024]

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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11383정성태12/4/201723396디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상 [1]
11382정성태12/4/201721933오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201718423.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201718451디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719136오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720620.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719881.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724272VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201719067오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201724166사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201723154오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726131사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719818오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719822오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721789사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727421.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727488개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201719135오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721380오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201723331사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723355사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719744오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722547오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722395오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721904오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726694사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...