Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1171. C# - BouncyCastle을 사용한 암호화/복호화 예제 [링크 복사], [링크+제목 복사],
조회: 8974
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

C# - BouncyCastle을 사용한 암호화/복호화 예제

마침 질문이 있군요. ^^

RSA 문의드립니다.
; https://www.sysnet.pe.kr/3/0/5619

개인적으로 BouncyCastle은 예전에 PEM 파일 읽는 용도로만 사용해봐서 암/복호화까지 해본 적은 없습니다. 그래도 뭐, 닷넷 BCL의 암/복호화랑 체계는 유사할 테니 비슷하지 않을까요? ^^

테스트를 위해 우선 BouncyCastle을 nuget으로부터 참조 추가하고,

[.NET Framework]
Install-Package BouncyCastle

[.NET Core/5+]
Install-Package BouncyCastle.NetCore

키를 초기화하기 위해 openssl로부터 pem 파일을 생성해 둡니다. 이에 대해서는 아래의 글에서 설명했습니다.

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

따라서 genrsa 옵션으로 키를 생성 후,

C:\temp> openssl genrsa 2048

출력되는 내용에서 BEGIN/END RSA PRIVATE KEY 내용을 뽑아,

-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAwA44z+R/dLyaiiOw3Gf29qtO+bHeVbvC3mKq8bnPTt53uNur
UCBCg1wkZXSCmweetFoZaE6rgAshcbSemKlBus/lkn/BK5ysYbJuXqcTK+oIW48r
...[생략]...
eMsXAoGAeWbmaxQPPdULzNILNzVx0EECtTvkNVprrpNMFdphVr+cC/oWe/velmXB
/6APbZcVCGIykvmZB+TolR/NKmA8vmpTov6HVQoXd3+fBtRziiaM+beb/XVOMdO6
NxRWJ9Max3N2OqgwHJ+AFRnO2aEVp7NcRK8SNXNlKufSSPOpSBo=
-----END RSA PRIVATE KEY-----

key.pem 파일로 저장해 둡니다. 자, 준비 작업은 이제 끝났으니 다음의 코드로 RSA 암/복호화를 할 수 있습니다.

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System.Text;

internal class Program
{
    static void Main(string[] args)
    {
        var pemReader = new PemReader(File.OpenText(@"key.pem"));
        var rsaKey = pemReader.ReadObject() as Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair;
        if (rsaKey == null)
        {
            return;
        }

        byte[] encrypted = EncryptData(rsaKey.Public, "test is good");
        Console.WriteLine(DecryptData(rsaKey.Private, encrypted)); // 출력 결과 "test is good"
    }

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

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

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

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

간단하죠? ^^




그나저나, "RSA/NONE/OAEPWITHSHA256ANDMGF1PADDING"라는 문자열 구성이 궁금해지는데요, 이에 대해 잘 설명한 문서가 있을까요? ^^ (아시는 분은 덧글 부탁드립니다.)

대신 CipherUtilities.GetCipher의 소스 코드를 보면 대략적인 해석이 나옵니다.

bouncycastle/crypto/src/security/CipherUtilities.cs 
; https://github.com/neoeinstein/bouncycastle/blob/master/crypto/src/security/CipherUtilities.cs

위의 소스 코드를 "RSA/NONE/OAEPWITHSHA256ANDMGF1PADDING" 옵션으로 축약해 보면 다음과 같이 OaepEncoding 인스턴스를 생성하는 것과 같습니다.

var encrypter = new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), null);

var decrypter = new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), null);

따라서, EncryptData, DecryptData 코드를 다음과 같이 변경하는 것도 가능합니다.

byte[] encrypted = EncryptData(rsaKey.Public, "test is good");
Console.WriteLine(DecryptData(rsaKey.Private, encrypted));

private static byte[] EncryptData(ICipherParameters keyParam, string data)
{
    var encrypter = new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), null);
    encrypter.Init(true, keyParam);

    byte[] plain = Encoding.UTF8.GetBytes(data);
    return encrypter.ProcessBlock(plain, 0, plain.Length);
}

private static string DecryptData(ICipherParameters keyParam, byte[] encrypted)
{
    var decrypter = new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), null);
    decrypter.Init(false, keyParam);

    byte [] decrypted = decrypter.ProcessBlock(encrypted, 0, encrypted.Length);
    return Encoding.UTF8.GetString(decrypted);
}

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/6/2023]

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

비밀번호

댓글 작성자
 




... 31  [32]  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12850정성태10/27/20219030오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20218139스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20219072스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218892스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218633스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218492.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216441오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216898스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125476오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218832스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218925.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219996.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219569.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218556VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20218176Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219386.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217773오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20217188VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20218128VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216601VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218931오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202110495.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/20218647.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/20218548스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202110770.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/20218367개발 환경 구성: 603. GoLand - WSL 환경과 연동
... 31  [32]  33  34  35  36  37  38  39  40  41  42  43  44  45  ...