TLS 인증서를 사용하여 RSA 알고리즘을 이용한 공개키/개인키 기반의 데이터 암호화 및 복호화를 할 수 있습니다.
먼저, 데이터 암호화를 위해서 TLS 인증서의 공개키를 가져오는 작업을 수행 합니다.
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Text;
var certificate = new X509Certificate2(@"인증서 경로", "비밀번호");
var publicKey = certificate.GetRSAPublicKey();
가져온 공개키를 이용해서 데이터를 암호화 합니다.
(예제에서는 plain text를 암호화하는 작업을 수행합니다.)
var plainText = "Hello, world!";
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var encryptedBytes = publicKey.Encrypt(plainBytes, RSAEncryptionPadding.OaepSHA256);
var encryptedText = Convert.ToBase64String(encryptedBytes);
Console.WriteLine(encryptedText);
//7ZfpMeUDxHkn2pCe8bMEGpmNzk3gYMHEzh5ZtH4wG5n8MEmnz4lj5CwmhNoyKdwj6mPnKVmVJBCLGbQD4edqa61lrSJ47U8W/3e6vJ5TE87e5s9o5Z4sBCdCu75uLenel5VZQllm70nyqR/9CZYt1PszArDj9KUeIJQcL00WH7ZR/dVPTPVYU6/zyFGwnNosF5tWpqjhTOoCEFeq9JL2OdeN+A==
다음으로, 암호화된 문자열을 개인키로 복호화하는 작업을 수행합니다.
TLS 인증서에서 개인키를 가져옵니다.
var privateKey = certificate.GetRSAPrivateKey();
가져온 개인키를 이요해서 암호화된 데이터를 복호화 합니다.
encryptedBytes = Convert.FromBase64String(encryptedText);
var decryptedBytes = privateKey.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA256);
var decryptedText = Encoding.UTF8.GetString(decryptedBytes);
Console.WriteLine(decryptedText);
//Hello, world!"
이렇게 TLS 인증서를 이용하여 RSA 알고리즘을 이용한 공개키/개인키 기반의 암호화 및 복호화를 수행할 수 있습니다.