2017-12-12 20 views
0

자체 서명 인증서를 만든 다음 어느 시점에서 읽으려고합니다. 프로그래밍 방식으로 pfx 파일로드 문제

는 PFX 파일을 생성하는 코드입니다 (source)

public static void CreateSelfSignedCertificate(string subjectName) 
     { 
      string pathToCertificate = CommonHelper.MapPath($"path_to_certificate/{TokenSigningCertificateName}"); 

      if (!File.Exists(pathToCertificate)) 
      { 
       // create DN for subject and issuer 
       var dn = new CX500DistinguishedName(); 
       dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); 

       // create a new private key for the certificate 
       CX509PrivateKey privateKey = new CX509PrivateKey(); 
       privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; 
       privateKey.MachineContext = true; 
       privateKey.Length = 2048; 
       privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited 
       privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; 
       privateKey.Create(); 

       // Use the stronger SHA512 hashing algorithm 
       var hashobj = new CObjectId(); 
       hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, 
        ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, 
        AlgorithmFlags.AlgorithmFlagsNone, "SHA512"); 

       // add extended key usage if you want - look at MSDN for a list of possible OIDs 
       var oid = new CObjectId(); 
       oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server 
       var oidlist = new CObjectIds(); 
       oidlist.Add(oid); 
       var eku = new CX509ExtensionEnhancedKeyUsage(); 
       eku.InitializeEncode(oidlist); 

       // Create the self signing request 
       var cert = new CX509CertificateRequestCertificate(); 
       cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); 
       cert.Subject = dn; 
       cert.Issuer = dn; // the issuer and the subject are the same 
       cert.NotBefore = DateTime.Now; 
       // this cert expires immediately. Change to whatever makes sense for you 
       cert.NotAfter = DateTime.Now; 
       cert.X509Extensions.Add((CX509Extension) eku); // add the EKU 
       cert.HashAlgorithm = hashobj; // Specify the hashing algorithm 
       cert.Encode(); // encode the certificate 

       // Do the final enrollment process 
       var enroll = new CX509Enrollment(); 
       enroll.InitializeFromRequest(cert); // load the certificate 
       enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name 
       string csr = enroll.CreateRequest(); // Output the request in base64 
       // and install it back as the response 
       enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, 
        csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password 
       // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes 
       var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption 
        PFXExportOptions.PFXExportChainWithRoot); 

       File.WriteAllText(pathToCertificate, base64encoded); 
      } 
     } 

을 그리고이 그것을로드 코드입니다 :

public static X509Certificate2 GetTokenSigningCertificate() 
     { 
      string pathToCertificate = CommonHelper.MapPath($"path_to_certificate/{TokenSigningCertificateName}"); 

      X509Certificate2 certificate = new X509Certificate2(pathToCertificate, ""); 

      return certificate; 
     } 

문제는 내가 얻고있다 :

인코딩 또는 디코딩 작업 중에 오류가 발생했습니다. System.Security.Cryptography.CryptographicException.ThrowCryptographicException에서 System.Security.Cryptography.CryptographicException

을 System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile (문자열 대신 파일명 (INT32 시간), IntPtr입니다 암호, UINT32 System.Security.Cryptography.X509Certificates.X509Certificate2..cto에서 System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile (문자열 파일 이름, 개체 암호, X509KeyStorageFlags keyStorageFlags)에서 dwFlags, 부울 persistKeySet, SafeCertContextHandle & pCertCtx) r (문자열 fileName, 문자열 암호)

아이디어가 있으십니까?

+1

base64 대신 바이너리를 사용하십시오. PFX에는 정의 된 PEM 헤더 이름이 없으며 base64 처리기가 없을 수도 있습니다. – bartonjs

+0

고마워, 바톤 니스. :) 제발, 답변을 최고의 답변으로 표시 할 수 있도록 귀하의 의견을 설정하십시오. –

답변

1

PFX를 base64로 내보내는 것 같습니다. 인증서, 키, PKCS # 7 BLOB 및 PKCS # 8 BLOB와 달리 PKCS # 12/PFX BLOB에는 정의 된 PEM 헤더가 없습니다. 결과적으로 PFX 읽기 파이프 라인에는 아마도 Base64 디코드가 첨부되어 있지 않습니다.

따라서 간단한 대답은 base64 대신 이진 인코딩 (따라서 File.WriteAllBytes())으로 방출 할 가능성이 높습니다.