(공개키를 담은) 자바의 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);
첨부한 파일은 위의 코드를 담은 간략한 테스트 프로젝트입니다.
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]