성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - 인증서 및 키 파일로부터 pfx/p12 파일을 생성하는 방법</h1> <p> 도구를 사용해서 인증서 및 개인키 파일, 그리고 그것들로부터 pfx 파일을 생성하는 것을 전에도 몇 번 다룬 적이 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 인증서 관련(CER, PVK, SPC, PFX) 파일 만드는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/863'>https://www.sysnet.pe.kr/2/0/863</a> JKS(Java Key Store)에 저장된 인증서를 ActiveX 코드 서명에 사용하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/882'>https://www.sysnet.pe.kr/2/0/882</a> .keystore 파일에 저장된 개인키 추출방법과 인증기관으로부터 온 공개키를 합친 pfx 파일 만드는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/1262'>https://www.sysnet.pe.kr/2/0/1262</a> Docker Desktop for Windows - kubectl proxy 없이 k8s 대시보드 접근 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12593#cert'>https://www.sysnet.pe.kr/2/0/12593#cert</a> </pre> <br /> 이번에는 프로그래밍으로 생성하는 방법을 다뤄보겠습니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 우선, 지난 글에서 이미 키 파일을 로드하는 방법에 대해 알아봤습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > openssl의 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 (2) ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12598'>https://www.sysnet.pe.kr/2/0/12598</a> </pre> <br /> 이제 남은 작업이라면, 인증서 파일을 로드 후 그것으로부터 pfx/p12 파일을 생성하기만 하면 됩니다.<br /> <br /> 실습을 위해 키와 인증서 데이터를 모두 가지고 있는 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12584#kubeconfig_path'>Kubernetes의 kubeconfig 파일</a>을 예로 들 텐데요, 따라서 kubconfig 파일에 등록된 사용자의 client-certificate-data, client-key-data를 읽어 우리가 사용할 수 있는 .NET 타입으로 다음과 같이 변환할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // Install-Package KubernetesClient string path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\.kube\config"); KubernetesClientConfiguration config = KubernetesClientConfiguration.BuildConfigFromConfigFile(path); // client-key-data로부터 RSACryptoServiceProvider 인스턴스 생성 string userKey = Encoding.UTF8.GetString(Convert.FromBase64String(config.ClientCertificateKeyData)); <span style='color: blue; font-weight: bold'>RSACryptoServiceProvider rsa</span> = PemKeyUtils.GetRSAProviderFromPem(userKey, isPrivate: true); // client-certificate-data로부터 X509Certificate2 인스턴스 생성 <span style='color: blue; font-weight: bold'>X509Certificate2 cert</span> = new X509Certificate2(Convert.FromBase64String(config.ClientCertificateData)); </pre> <br /> 그래서 위의 cert, rsa 인스턴스를 조합해 pfx/.p12 파일을 만드는 것이 가능하겠으나,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // How do I create a PKCS12 .p12 file in C#? // ; <a target='tab' href='https://stackoverflow.com/questions/2039364/how-do-i-create-a-pkcs12-p12-file-in-c'>https://stackoverflow.com/questions/2039364/how-do-i-create-a-pkcs12-p12-file-in-c</a> cert.PrivateKey = rsaKey; byte [] pfx = cert.Export(X509ContentType.Pkcs12, "...password..."); </pre> <br /> 아쉽게도 .NET Core 부터는 위와 같이 하는 경우 set_PrivateKey 단계에서 "System.PlatformNotSupportedException: Operation is not supported on this platform." 예외가 발생합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 어쩔 수 없군요, 다시 BouncyCastle의 힘에 의지하면, ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Install-Package BouncyCastle </pre> <br /> 다음과 같이 간단하게 pfx 파일을 만들 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > static void Main(string[] args) { string path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\.kube\config"); KubernetesClientConfiguration config = KubernetesClientConfiguration.BuildConfigFromConfigFile(path); string userKey = Encoding.UTF8.GetString(Convert.FromBase64String(config.ClientCertificateKeyData)); byte [] userCrt = Convert.FromBase64String(config.ClientCertificateData); StringReader sr = new StringReader(userKey); PemReader pemReader = new PemReader(sr); AsymmetricCipherKeyPair keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair; <span style='color: blue; font-weight: bold'>AsymmetricKeyParameter KeyParameter = keyPair.Private;</span> X509CertificateParser p = new X509CertificateParser(); <span style='color: blue; font-weight: bold'>X509Certificate cert</span> = p.ReadCertificate(userCrt); <span style='color: blue; font-weight: bold'>Pkcs12Store store</span> = new Pkcs12StoreBuilder().Build(); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(KeyParameter); X509CertificateEntry certEntry = new X509CertificateEntry(cert); // alias == Friendly Name <span style='color: blue; font-weight: bold'>store.SetKeyEntry("myCert", keyEntry, new X509CertificateEntry[] { certEntry });</span> using (FileStream fs = File.OpenWrite("test.pfx")) { store.Save(fs, password: "test".ToCharArray(), new SecureRandom()); } } </pre> <br /> 실제로 저렇게 해서 출력한 test.pfx를 탐색기에서 두 번 클릭해 인증서를 정상적으로 등록할 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 하는 김에, 인증서를 등록하는 부분도 코드로 자동화를 해볼까요? ^^ 이 부분은 전에 소개한 글이 있으므로,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - 인증서를 윈도우에 설치하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/11719'>https://www.sysnet.pe.kr/2/0/11719</a> </pre> <br /> 최종 소스 코드는 다음과 같이 조합할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using k8s; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.X509; using System; using System.IO; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Text; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\.kube\config"); KubernetesClientConfiguration config = KubernetesClientConfiguration.BuildConfigFromConfigFile(path); string userKey = Encoding.UTF8.GetString(Convert.FromBase64String(config.ClientCertificateKeyData)); byte [] userCrt = Convert.FromBase64String(config.ClientCertificateData); StringReader sr = new StringReader(userKey); PemReader pemReader = new PemReader(sr); AsymmetricCipherKeyPair keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair; AsymmetricKeyParameter KeyParameter = keyPair.Private; X509CertificateParser p = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate cert = p.ReadCertificate(userCrt); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(KeyParameter); X509CertificateEntry certEntry = new X509CertificateEntry(cert); // alias == Friendly Name store.SetKeyEntry("myCert", keyEntry, new X509CertificateEntry[] { certEntry }); char[] password = "test".ToCharArray(); /* .pfx/.p12 파일로 저장 using (FileStream fs = File.OpenWrite("test.pfx")) { store.Save(fs, password, new SecureRandom()); } */ // C# - 인증서를 윈도우에 설치하는 방법 // ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/11719'>https://www.sysnet.pe.kr/2/0/11719</a> using (MemoryStream ms = new MemoryStream()) { store.Save(ms, password, new SecureRandom()); byte[] pfxBytes = ms.ToArray(); unsafe { fixed (char* ptr = password) { SecureString secureText = new SecureString(ptr, password.Length); X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadWrite); certStore.Add(new X509Certificate2(pfxBytes, secureText)); certStore.Close(); } } } } } } </pre> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1744&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 부가적으로, 다음의 "Chilkat .NET" 라이브러리를 사용한 방법도 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Chilkat .NET - (C#) Create .pfx/.p12 from Certificate and Private Key PEM Files ; <a target='tab' href='https://www.example-code.com/csharp/pfx_create_from_pem_files.asp'>https://www.example-code.com/csharp/pfx_create_from_pem_files.asp</a> </pre> <br /> 그렇긴 한데, 재미있게도 "KubernetesClient"를 사용하는 경우라면 어차피 해당 패키지가 BouncyCastle에 의존하고 있으므로 별도의 라이브러리를 다시 추가할 의미가 없습니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
9394
(왼쪽의 숫자를 입력해야 합니다.)