How to create a snk from pfx / cer?

前端 未结 3 835
误落风尘
误落风尘 2020-12-23 13:03

Microsoft seems to have created a certification jungle, that is hard to understand.

  • Microsoft X.509 certificate (.cer)
  • Personal Information Exchange
3条回答
  •  礼貌的吻别
    2020-12-23 13:51

    A little clarification about your mentioned file types:

    • .cer-files are X.509 Certificates
    • .pfx-files are encrypted X.509 Certificates using a password-based symmetric key, also see PKCS #12 (Wikipedia)
    • .snk-files only contain the RSA key (public/private or public only)

    It doesn't matter if you sign an assembly using .pfx-files or .snk-files, it will get strong named either way. Storing the RSA key as a encrypted certificate (.pfx) is of course more secure than storing just the unencrypted key (.snk).

    You can easily extract the key from those files in code using class System.Security.Cryptography.X509Certificates.X509Certificate2.

    To extract key from .pfx:

    /// 
    /// Converts .pfx file to .snk file.
    /// 
    /// .pfx file data.
    /// .pfx file password.
    /// .snk file data.
    public static byte[] Pfx2Snk(byte[] pfxData, string pfxPassword)
    {
        // load .pfx
        var cert = new X509Certificate2(pfxData, pfxPassword, X509KeyStorageFlags.Exportable);
    
        // create .snk
        var privateKey = (RSACryptoServiceProvider)cert.PrivateKey;
        return privateKey.ExportCspBlob(true);
    }
    

    Use privateKey.ExportCspBlob(false) to extract public key only! (e.g. for delay-signing of assemblies)

提交回复
热议问题