代码之家  ›  专栏  ›  技术社区  ›  iliyan tanev

以编程方式加载pfx文件时出现问题

  •  1
  • iliyan tanev  · 技术社区  · 8 年前

    我试图创建一个自签名证书,然后在某个时候读取它。

    以下是创建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;
            }
    

    问题是我得到了:

    编码或解码操作期间出错。 系统安全密码学。加密异常

    在 系统安全密码学。加密异常。ThrowCryptographicException(Int32 hr)在 系统安全密码学。X509证书。X509Utils_LoadCertFromFile(字符串 fileName、IntPtr password、UInt32 dwFlags、Boolean persistKeySet、, SafeCertContextHandle&pCertCtx) 系统安全密码学。X509证书。X509证书。LoadCertificateFromFile(字符串 文件名、对象密码、X509KeyStorageFlags keyStorageFlags)位于 系统安全密码学。X509证书。X509证书2。。ctor(字符串 文件名,字符串密码)

    有什么想法吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   bartonjs    8 年前

    您似乎正在将PFX导出为base64。与证书、密钥、PKC#7 blob和PKC#8 blob不同,PKC#12/PFX blob没有定义的PEM头。因此,PFX读取管道可能没有连接Base64解码。

    因此,简单的答案很可能通过二进制编码发出(因此 File.WriteAllBytes() )而不是base64。

    推荐文章