Install WordPress on IIS

WordPress is a blog publishing application and content management system. According to wordpress.org, WordPress is “a state-of-the-art semantic personal publishing platform with a focus on aesthetics, Web standards, and usability.” The following sections describe how to install and configure WordPress for use with FastCGI on Internet Information Services 7 (IIS 7) and above. This document assumes that you have completed the setup and configuration of the FastCGI extension and PHP libraries.

Using FastCGI to Host PHP Applications on IIS 7

Enable FastCGI Support in IIS

Windows Server 2008

Go to Server Manager -> Roles -> Add Role Services. On the Select Role Servicespage, select the CGI check box. This enables both the CGI and FastCGI services.

image2

Windows Vista SP1

Go to Control Panel -> Programs and Features -> Turn Windows features on or off. In the Windows Features dialog box, select the CGI check box. This enables both the CGI and FastCGI services.

image3

Install and Configure PHP

It is recommended that you use a non-thread safe build of PHP with IIS FastCGI. A non-thread safe build of PHP provides significant performance gains over the standard build by not doing any thread-safety checks, which are not necessary, since FastCGI ensures a single threaded execution environment.

To install PHP:

  1. Download the latest non-thread safe zip package with binaries of PHP:http://www.php.net/downloads.php.
  2. Unpack the files to the directory of your choice (e.g.C:\PHP). Rename the php.ini-recommended file to php.ini.
  3. Open the php.ini file. Uncomment and modify the settings as follows:
    • Setimpersonate = 1. FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.
    • Setfix_pathinfo=1. cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. Previously, PHP behavior was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not define PATH_INFO. For more information about PATH_INFO, see the cgi specifications. Setting this value to 1 will cause PHP CGI to fix its paths to conform to the specifications.
    • Setforce_redirect = 0.
    • Setopen_basedir to point to the folder or network path where the content of the Web site(s) is located.
    • Setextension_dir to point to the location where the PHP extensions are located. Typically, for PHP 5.2.X the value would be set as extension_dir = “./ext”
    • Enable the required PHP extension by un-commenting the corresponding lines, for example:
extension=php_mssql.dll
extension=php_mysql.dll
  1. Open a command prompt, and run the following command to verify that PHP installed successfully:
consoleCopy
C:\PHP>php –info

If PHP installed correctly and all its dependencies are available on the machine, this command will output the current PHP configuration information.

Configure IIS to Handle PHP Requests

For IIS to host PHP applications, you must add a handler mapping that tells IIS to pass all PHP-specific requests to the PHP application framework by using the FastCGI protocol.

Configure IIS to handle PHP requests by using IIS Manager

  • Open IIS Manager. At the server level, double-click Handler Mappings.

image4

  • In the Actions pane, click Add Module Mapping…. In the Add Module Mapping dialog box, specify the configuration settings as follows:
    • Request path: *.php
    • Module: FastCgiModule
    • Executable: “C:[Path to your PHP installation]\php-cgi.exe”
    • Name: PHP via FastCGI
  • Click OK.

image5

  • In the Add Module Mapping confirmation dialog box that asks if you want to create a FastCGI application for this executable, click Yes.

image6

  • Test that the handler mapping works correctly by creating a phpinfo.php file in theC:\inetpub\wwwroot folder that contains the following code:
   <?php phpinfo(); ?>
  • Open a browser and navigate to http://localhost/phpinfo.php. If everything was setup correctly, you will see the standard PHP information page.

image6

Generate PDF from HTML & Integrate Digital Signature into PDF using iTextSharp in C#

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

public partial class _Default : System.Web.UI.Page
{
    public enum HashType
    {
        SHA1withDSA, //-- DSA
        SHA1withECDSA, //
        SHA224withECDSA, // ECDSA with SHA1 and SHA2 support
        SHA256withECDSA, //
        SHA384withECDSA, //
        SHA512withECDSA, //
        MD2withRSA, // --
        MD5withRSA, // --
        SHA1withRSA, // --
        SHA224withRSA, // -- RSA with MD2, MD5, SHA1, SHA2 and RIPEMD
        SHA256withRSA, // --
        SHA384withRSA, // --
        SHA512withRSA, // --
        RIPEMD160withRSA, // -- RIPEMD hash
        RIPEMD128withRSA, // --
        RIPEMD256withRSA, // --
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        CreatePDF();
    }

    private void CreatePDF()
    {
        //Create a byte array that will eventually hold our final PDF
        Byte[] bytes;

        //Boilerplate iTextSharp setup here
        //Create a stream that we can write to, in this case a MemoryStream
        using (var ms = new MemoryStream())
        {
            //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
            using (var doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f))
            {
                //Create a writer that's bound to our PDF abstraction and our stream
                using (var writer = PdfWriter.GetInstance(doc, ms))
                {
                    //Open the document for writing
                    doc.Open();
                    string contents = File.ReadAllText(@"F:\PROJECTS\WebSite6\HTML\a.html");

                    /**************************************************
                     * Use the XMLWorker to parse the HTML.           *
                     * Only inline CSS and absolutely linked          *
                     * CSS is supported                               *
                     * ************************************************/
                    //XMLWorker also reads from a TextReader and not directly from a string
                    using (var srHtml = new StringReader(contents))
                    {
                        //Parse the HTML
                        iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                    }                   
                    doc.Close();
                }
            }
            //After all of the PDF "stuff" above is done and closed but **before** we
            //close the MemoryStream, grab all of the active bytes from the stream
            bytes = ms.ToArray();
        }

        //Now we just need to do something with those bytes.
        //Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
        //You could also write the bytes to a database in a varbinary() column (but please don't) or you
        //could pass them to another function for further PDF processing.
        var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
        System.IO.File.WriteAllBytes(testFile, bytes);
        //===================
        GeneratorKey();
        //===================

        Stream fs = File.OpenRead(@"F:/PROJECTS/WebSite6/HTML/TestCert.pfx");

        string sourceDocument = testFile;
        string destinationPath = testFile.Replace(".pdf", "_signed.pdf");
        Stream privateKeyStream = fs;
        string keyPassword = "123";
        string reason = "I am an Author";
        string location = "Mumbai";

        _Default.signPdfFile(sourceDocument, destinationPath, privateKeyStream, keyPassword, reason, location);

        fs.Close();
    }

    private void GeneratorKey()
    {
        // Keypair Generator
        RsaKeyPairGenerator kpGenerator = new RsaKeyPairGenerator();
        kpGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

        // Create a keypair
        AsymmetricCipherKeyPair kp = kpGenerator.GenerateKeyPair();

        // Certificate Generator
        X509V3CertificateGenerator cGenerator = new X509V3CertificateGenerator();
        cGenerator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
        cGenerator.SetSubjectDN(new X509Name("CN=" + "domain.com"));
        cGenerator.SetIssuerDN(new X509Name("CN=" + "Amit"));
        cGenerator.SetNotBefore(DateTime.Now);
        cGenerator.SetNotAfter(DateTime.Now.Add(new TimeSpan(365, 0, 0, 0))); // Expire in 1 year
        cGenerator.SetSignatureAlgorithm(HashType.SHA256withRSA.ToString()); // See the Appendix Below for info on the hash types supported by Bouncy Castle C#
        cGenerator.SetPublicKey(kp.Public); // Only the public key should be used here!
        X509Certificate cert = cGenerator.Generate(kp.Private); // Create a self-signed cert

        byte[] encoded = cert.GetEncoded();
        using (FileStream outStream = new FileStream("F:/PROJECTS/WebSite6/HTML/TestCert.der", FileMode.Create, FileAccess.ReadWrite))
        {
            outStream.Write(encoded, 0, encoded.Length);
        }

        // Create the PKCS12 store
        Pkcs12Store store = new Pkcs12StoreBuilder().Build();

        // Add a Certificate entry
        X509CertificateEntry certEntry = new X509CertificateEntry(cert);
        store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

        // Add a key entry
        AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(kp.Private);
        store.SetKeyEntry(cert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

        // Save to the file system
        using (var filestream = new FileStream(@"F:/PROJECTS/WebSite6/HTML/TestCert.pfx", FileMode.Create, FileAccess.ReadWrite))
        {
            store.Save(filestream, "123".ToCharArray(), new SecureRandom());
        }
    }

    public static void signPdfFile(string sourceDocument, string destinationPath, Stream privateKeyStream, string keyPassword, string reason, string location)
    {
        Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());
        privateKeyStream.Dispose();

        //then Iterate throught certificate entries to find the private key entry
        string alias = null;
        foreach (string tAlias in pk12.Aliases)
        {
            if (pk12.IsKeyEntry(tAlias))
            {
                alias = tAlias; break;
            }
        }

        var pk = pk12.GetKey(alias).Key;
        // reader and stamper
        PdfReader reader = new PdfReader(sourceDocument);
        using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite))
        {
            using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
            {
                // appearance
                PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                //appearance.Image = new iTextSharp.text.pdf.PdfImage();
                appearance.Reason = reason; appearance.Location = location;
                appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), 1, "Icsi-Vendor");
                // digital signature
                IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
                MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);
                stamper.Close();
            }
        }
    }
}

Create a Basic Certificate in C# .NET

Overview

Before jumping into the actual code, I want to point out what will need to be done to generate a Certificate and save it in either DER or PKCS12 format. This is done so you have an at-a-glance view of what needs to be coded to make this work. The steps below are bouncy castle specific, although the general principles probably apply to a number of crypto APIs.

Generate the keys and the Certificate:

  • Create an Asymmetric keypair Generator
  • Generate the Asymmetric keypair
  • Create a Certificate Generator
  • Assign properties to the Certificate generator (CN, Bitstrength, Validity period, etc…)
  • Generate a Certificate signed by the issuer’s private certificate (we’ll be doing self signed here)

Package as a DER:

  • Grab a DER encoded byte array from the certificate
  • Use a .NET FileStream to write the bytes out to the Hard drive. That’s it!

Package as a PKCS12:

  • Create a new PKCS12 Store builder
  • Add a Certificate entry to the store
  • Add a private key entry to the store
  • Write out the PKCS12 store to a .NET MemoryStream
  • Save the bytes to a FileStream (You could probably save directly to a FileStream)

 

Section 0: .NET using statements

One thing that bugs me a lot about Stack Overflow is that sometimes your questions get edited to remove the using statements that go at the top of the source file. This is frustrating since sometimes it can be difficult to find out which namespace a class ‘lives’ in. In this article I’m going to list the using statements that will be needed to make a Certificate in Bouncy Castle:

using System;
using System.IO;

using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

 

Create the Asymmetric keys and the Certificate

First, create a keypair generator. In this example we are instantiating a new instance of RsaKeyPairGenerator and feeding it the appropriate KeyGenerationParameters and the Bit Strength of the resulting keys:

// Keypair Generator
RsaKeyPairGenerator kpGenerator = new RsaKeyPairGenerator();
kpGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

Generate the keypair using the GenerateKeyPair() method:

// Create a keypair
AsymmetricCipherKeyPair  kp = kpGenerator.GenerateKeyPair();

Instantiate a new X509V3CertificateGenerator and assign it the Certificate Properties you want the final certificate to have. In this example we create a couple of X509Name objects that hold the Common Name (Certificate DN) and IssuerDN. We also use a BigInteger to come up with a serial number and a couple of DateTime objects to store the valid from/to dates:

// Certificate Generator
X509V3CertificateGenerator cGenerator = new X509V3CertificateGenerator();
cGenerator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
cGenerator.SetSubjectDN(new X509Name("CN=" + "some.machine.domain.tld"));
cGenerator.SetIssuerDN(new X509Name("CN=" + "issuer's name"));
cGenerator.SetNotBefore(DateTime.Now);
cGenerator.SetNotAfter(DateTime.Now.Add(new TimeSpan(365, 0, 0, 0))); // Expire in 1 year
cGenerator.SetSignatureAlgorithm(HashType.SHA1withDSA.ToString()); // See the Appendix Below for info on the hash types supported by Bouncy Castle C#
cGenerator.SetPublicKey(kp.Public); // Only the public key should be used here!

Generate a Certificate signed by the issuer’s private key. In this case we’re making a self-signed certificate so we’ll use the private key that was generated above:

X509Certificate cert = cGenerator.Generate(kp.Private); // Create a self-signed cert

Congratulations! At this point you have valid X509 Certificate. Read on for how to get the bytes written out to the file system.
Note: This is NOT the same as a .NET X509Certificate2. Conversions need to be done when working with both types (outside the scope of this article)

 

Option 1: Package and save as a DER encoded file

This is the easiest format to save your certificate in. It involves obtaining the DER encoded bytes of the certificate object and writing them out to the file system.

Get the encoded bytes with the GetEncoded() method that is available on all certificate objects:

byte[] encoded = cert.GetEncoded();

Now, write the bytes out to the file system using a FileStream:

using (FileStream outStream = new FileStream("c:\someCertname.der", FileMode.Create, FileAccess.ReadWrite)) {
outStream.Write(encoded, 0, encoded.Length);
}

If everything works you should be able to double-click on the file in the Windows Explorer and import the certificate using the Cert import wizard.

 

Option 2: Package and save as a PKCS12 file (Includes the private key)

This is a little bit more complex since we need to create a PKCS12 store before writing anything out. On the whole it is not too difficult, though.

Create AND build a new Pkcs12Store object. This will let us create the actual PKCS12 store:

// Create the PKCS12 store
Pkcs12Store store = new Pkcs12StoreBuilder().Build();

Add a certificate entry to the store. The certificate needs to be converted to an X509CertificateEntry object for this to work. Once we have the data in the correct type, we can use the SetCertificateEntry method to add the cert data to the PKCS#12 store. It needs to have an alias so I set it to the certificate’s DN in this example:

// Add a Certificate entry
X509CertificateEntry certEntry = new X509CertificateEntry(cert);
store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

Next add an entry for the Certificate’s Private key. This is like the CertificateEntry where we need to give it an alias. I just use the Certificate’s DN + “_key” and it seems to work for me. One additional thing here is that you need to include the X509CertificateEntry that are associated with the private key in an array form. Since we only have a self-signed certificate this example will only have one certificate in the ‘chain’. I’m not sure how this would work with more than one certificate:

// Add a key entry
AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(kp.Private);
store.SetKeyEntry(cert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

At this point you have everything you need to save the PKCS#12 store to the file system. You just need to write it out. Here is a quick way to perform the ‘save’ operation:

// Save to the file system
  using (var filestream = new FileStream(@"c:\certificatename.pfx", FileMode.Create, FileAccess.ReadWrite)) {
    store.Save(filestream, "passwordProtected".ToCharArray(), new SecureRandom());
  }
    1. We use the Save() method that is avaialble on the BouncyCastle Pkcs12Store object to write out to a FileStream
    2. Be sure to specify a password you can remember. You will be prompted for the password when you use the store.

 

Appendix: Hash Types supported by Bouncy Castle (C#.NET)

This enum can be used to simplify your code. Rather than passing in “SHA1withDSA” (String literal) you can do HashType.SHA1withDSA.ToString()

I like to use enums where possible since it restricts the number of ‘magic literals’ in my code.

public enum HashType {
  SHA1withDSA, //-- DSA
  SHA1withECDSA, //
  SHA224withECDSA, // ECDSA with SHA1 and SHA2 support
  SHA256withECDSA, //
  SHA384withECDSA, //
  SHA512withECDSA, //
  MD2withRSA, // --
  MD5withRSA, // --
  SHA1withRSA, // --
  SHA224withRSA, // -- RSA with MD2, MD5, SHA1, SHA2 and RIPEMD
  SHA256withRSA, // --
  SHA384withRSA, // --
  SHA512withRSA, // --
  RIPEMD160withRSA, // -- RIPEMD hash
  RIPEMD128withRSA, // --
  RIPEMD256withRSA, // --
}

 

Reference: https://boredwookie.net/blog/m/bouncy-castle-create-a-basic-certificate