.NET Fiddle

CSharp · Console

/Program.cs

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class Program
{

    public static void Main()
    {
        String facebookCertificateBase64 =
                "MIIH5DCCBsygAwIBAgIQDACZt9eJyfZmJjF+vOp8HDANBgkqhkiG9w0BAQsFADBw" +
                "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3" +
                "d3cuZGlnaWNlcnQuY29tMS8wLQYDVQQDEyZEaWdpQ2VydCBTSEEyIEhpZ2ggQXNz" +
                "dXJhbmNlIFNlcnZlciBDQTAeFw0xNjEyMDkwMDAwMDBaFw0xODAxMjUxMjAwMDBa" +
                "MGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRMwEQYDVQQHEwpN" +
                "ZW5sbyBQYXJrMRcwFQYDVQQKEw5GYWNlYm9vaywgSW5jLjEXMBUGA1UEAwwOKi5m" +
                "YWNlYm9vay5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASg8YyvpzmIaFsT" +
                "Vg4VFbSnRe8bx+WFPCsE1GWKMTEi6qOS7WSdumWB47YSdtizC0Xx/wooFJxP3HOp" +
                "s0ktoHbTo4IFSjCCBUYwHwYDVR0jBBgwFoAUUWj/kK8CB3U8zNllZGKiErhZcjsw" +
                "HQYDVR0OBBYEFMuYKIyhcufiMqmaPfINoYFWoRqLMIHHBgNVHREEgb8wgbyCDiou" +
                "ZmFjZWJvb2suY29tgg4qLmZhY2Vib29rLm5ldIIIKi5mYi5jb22CCyouZmJjZG4u" +
                "bmV0ggsqLmZic2J4LmNvbYIQKi5tLmZhY2Vib29rLmNvbYIPKi5tZXNzZW5nZXIu" +
                "Y29tgg4qLnh4LmZiY2RuLm5ldIIOKi54eS5mYmNkbi5uZXSCDioueHouZmJjZG4u" +
                "bmV0ggxmYWNlYm9vay5jb22CBmZiLmNvbYINbWVzc2VuZ2VyLmNvbTAOBgNVHQ8B" +
                "Af8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMHUGA1UdHwRu" +
                "MGwwNKAyoDCGLmh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9zaGEyLWhhLXNlcnZl" +
                "ci1nNS5jcmwwNKAyoDCGLmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zaGEyLWhh" +
                "LXNlcnZlci1nNS5jcmwwTAYDVR0gBEUwQzA3BglghkgBhv1sAQEwKjAoBggrBgEF" +
                "BQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzAIBgZngQwBAgIwgYMG" +
                "CCsGAQUFBwEBBHcwdTAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQu" +
                "Y29tME0GCCsGAQUFBzAChkFodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGln" +
                "aUNlcnRTSEEySGlnaEFzc3VyYW5jZVNlcnZlckNBLmNydDAMBgNVHRMBAf8EAjAA" +
                "MIICsAYKKwYBBAHWeQIEAgSCAqAEggKcApoAdgCkuQmQtBhYFIe7E6LMZ3AKPDWY" +
                "BPkb37jjd80OyA3cEAAAAVjl02IEAAAEAwBHMEUCIQDvWFsUeqWE/xwIYcXPvbb5" +
                "ExzfHBZTNwfnUf4RPO/lBgIgdOGmr0j7+u8/S+7tfFw71ZEjqpwJELl/sEFuQdPn" +
                "pwQBLwCsO5rtf6lnR1cVnm19V1Zy+dmBAJQem97/7KExO3V4LQAAAVjl02IoAAAE" +
                "AQEAYvnMV+BfP3Wrk4yFQE/Zx5WsjSabYOpLj1Tj5xFaoVoHdGqLCf/Hi+Vv0IRy" +
                "ePKFBCSW0+3eA589+WnCDMwcJlBYeZV8MlvHFZg3a66Uhx/OAvoetb0mCtUpnmIE" +
                "UwLX/eMNEvjg2qTH3/33ysCo2l25+/EcR8upF+2KIcmnk5WwaJzfq7cFPQc4Cvcz" +
                "mTHasJi/jmVaIaJ9HC50g3dx584TQX26lDLddF/Li4uEbJ7TSopnTzjQdWBtWbMF" +
                "h3bcfhFCKaqK2kIJV3bgup5HibEnZ2LPm6lekY072ZFCGM4QYc4ukqzou2JWCRmG" +
                "o0dMHJhnvQXpnIQGwATqCD4Q1AB2AFYUBpov18Ls0/XhvUSyPsdGdrm8mRFcwO+U" +
                "mFXWidDdAAABWOXTYrkAAAQDAEcwRQIgGhXXbwUO5bD4Ts/Q0gqZwUS2vl/A4Hem" +
                "k7ovxl82v9oCIQCbtkflDXbcunY4MAQCbKlnesPGc/nftA84xDhJpxFHWQB3AO5L" +
                "vbd1zmC64UJpH6vhnmajD35fsHLYgwDEe4l6qP3LAAABWOXTZBEAAAQDAEgwRgIh" +
                "AKubngQoa5Iak8eCOrffH7Xx3AP1NMb5pFw35nt2VSeRAiEA47Kq1UQcDXIEsV+W" +
                "nuPd9LM5kpdeu0+TiHKtTLRQr0swDQYJKoZIhvcNAQELBQADggEBADrNSsoonbj1" +
                "YGjwy9t9wP9+kZBwrNMO2n5N5fQNhGawkEAX+lXlzgm3TqYlTNi6sCFbPBAErim3" +
                "aMVlWuOlctgnjtAdmdWZ4qEONrBLHPGgukDJ3Uen/EC/gwK6KdBCb4Ttp6MMPY1c" +
                "hb/ciTLi3QUUU4h4OJWqUjvccBCDs/LydNjKWZZTxLJmxRSmfpyCU3uU2XHHMNlo" +
                "8UTIlqZsOtdqhg7/Q/cvMDHDkcI/tqelmg0MD2H9KpcmAvVkwgjn+BVpv5HELl+0" +
                "EP0UhYknI1B6LBecJuj7jI26eXZdX35CYkpI/SZA9KK+OYKHh6vCxKqnRZ9ZQUOj" +
                "XnIWKQeV5Hg=";

        //Decode base64 into bytes blob
        Byte[] certBlob = System.Convert.FromBase64String(facebookCertificateBase64);

        //Create certificate from blob
        var cert = new X509Certificate2(certBlob);

        //Get certificate PublicKeyPinning hash (sha256 hash of the SubjectPublicKeyInfo section)
        String publicKeyHash = cert.GetPublicKeyPinningHash();

        if (publicKeyHash != "hUIG87ch71EZQYhZBEkq2VKBLjhussUw7nR8wyuY7rY=")
            throw new Exception("Self-test failed");

        String s = String.Format("Public-Key-Pins: pin-sha256=\"{0}\"; max-age=31536000", publicKeyHash);
        Console.WriteLine(s);
    }
}

public static class X509Certificate2Helper
{
    //Public domain: No attribution required.

    /// <summary>
    /// Returns the base64 encoded Public Key Pinning hash of the certificate.
    /// </summary>
    /// <param name="Certificate"></param>
    /// <returns>A base-64 encoded string that represents the hash of the certifcate's SubjectPublicKeyInfo</returns>
    public static String GetPublicKeyPinningHash(this X509Certificate2 Certificate)
    {
        //Get the SubjectPublicKeyInfo member of the certificate
        Byte[] subjectPublicKeyInfo = GetSubjectPublicKeyInfoRaw(Certificate);

        //Take the SHA2-256 hash of the DER ASN.1 encoded value
        Byte[] digest;
        using (var sha2 = new SHA256Managed())
        {
            digest = sha2.ComputeHash(subjectPublicKeyInfo);
        }

        //Convert hash to base64
        String hash = Convert.ToBase64String(digest);

        return hash;
    }

    /// <summary>
    /// Returns the raw ASN.1 DER bytes of the certificate's SubjectPublicKeyInfo section
    /// </summary>
    /// <param name="Certificate"></param>
    /// <returns>A byte array containing ASN.1 DER encoded SubjectPublicKeyInfo</returns>
    public static Byte[] GetSubjectPublicKeyInfoRaw(this X509Certificate2 Certificate)
    {
        //Public domain: No attribution required.
        Byte[] rawCert = Certificate.GetRawCertData();

        /*
         Certificate is, by definition:
          
            Certificate  ::=  SEQUENCE  {
                tbsCertificate       TBSCertificate,
                signatureAlgorithm   AlgorithmIdentifier,
                signatureValue       BIT STRING  
            }

           TBSCertificate  ::=  SEQUENCE  {
                version         [0]  EXPLICIT Version DEFAULT v1,
                serialNumber         CertificateSerialNumber,
                signature            AlgorithmIdentifier,
                issuer               Name,
                validity             Validity,
                subject              Name,
                subjectPublicKeyInfo SubjectPublicKeyInfo,
                issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version MUST be v2 or v3
                subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version MUST be v2 or v3
                extensions      [3]  EXPLICIT Extensions       OPTIONAL  -- If present, version MUST be v3
            }

        So we walk to ASN.1 DER tree in order to drill down to the SubjectPublicKeyInfo item
        */
        Byte[] list = AsnNext(ref rawCert, true); //unwrap certificate sequence
        Byte[] tbsCertificate = AsnNext(ref list, false); //get next item; which is tbsCertificate
        list = AsnNext(ref tbsCertificate, true); //unwap tbsCertificate sequence

        Byte[] version = AsnNext(ref list, false); //tbsCertificate.Version
        Byte[] serialNumber = AsnNext(ref list, false); //tbsCertificate.SerialNumber
        Byte[] signature = AsnNext(ref list, false); //tbsCertificate.Signature
        Byte[] issuer = AsnNext(ref list, false); //tbsCertificate.Issuer
        Byte[] validity = AsnNext(ref list, false); //tbsCertificate.Validity
        Byte[] subject = AsnNext(ref list, false); //tbsCertificate.Subject        
        Byte[] subjectPublicKeyInfo = AsnNext(ref list, false); //tbsCertificate.SubjectPublicKeyInfo        

        return subjectPublicKeyInfo;
    }

    static Byte[] AsnNext(ref Byte[] buffer, Boolean unwrap)
    {
        //Public domain: No attribution required.
        Byte[] result;

        if (buffer.Length < 2)
        {
            result = buffer;
            buffer = new Byte[0];
            return result;
        }

        int index = 0;
        Byte entityType = buffer[index];
        index += 1;

        int length = buffer[index];
        index += 1;

        int lengthBytes = 1;
        if (length >= 0x80)
        {
            lengthBytes = length & 0x0F; //low nibble is number of length bytes to follow
            length = 0;

            for (int i = 0; i < lengthBytes; i++)
            {
                length = (length << 8) + (int)buffer[2 + i];
                index += 1;
            }
            lengthBytes++;
        }

        int copyStart;
        int copyLength;
        if (unwrap)
        {
            copyStart = 1 + lengthBytes;
            copyLength = length;
        }
        else
        {
            copyStart = 0;
            copyLength = 1 + lengthBytes + length;
        }
        result = new Byte[copyLength];
        Array.Copy(buffer, copyStart, result, 0, copyLength);

        Byte[] remaining = new Byte[buffer.Length - (copyStart + copyLength)];
        if (remaining.Length > 0)
            Array.Copy(buffer, copyStart + copyLength, remaining, 0, remaining.Length);
        buffer = remaining;

        return result;
    }

}
;