簡體   English   中英

以編程方式加載pfx文件時出現問題

[英]Problems loading a pfx file programmatically

我正在嘗試創建一個自簽名證書,然后在某個時候閱讀它。

這是用於創建pfx文件的代碼:( 源)

 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

在System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)處.X509Certificate.LoadCertificateFromFile(字符串fileName,對象密碼,X509KeyStorageFlags keyStorageFlags)位於System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(字符串fileName,字符串密碼)

有任何想法嗎?

您似乎將PFX導出為base64。 與證書,密鑰,PKCS#7 Blob和PKCS#8 Blob不同,PKCS#12 / PFX Blob沒有定義的PEM標頭。 結果,PFX讀取管道可能沒有附加的Base64解碼。

因此,簡單的答案很可能使用二進制編碼(以及File.WriteAllBytes() )而不是base64發出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM