Mar 30, 2017

OpenSSL | Creating Certification Authority & Domain Certificates for IIS

Setup

Download the OpenSSL binaries from this location.
(Please note that version 1.0.2 works better in windows)

Extract the binaries at location:
C:\OpenSSL\
The binaries will be downloaded in bin folder. Now create a demo folder at this location

Add the following location to windows PATH variable.
C:\OpenSSL\bin
Create 2 Environment Variables:
set RANDFILE=C:\OpenSSL\demo\.rnd
set OPENSSL_CONF=C:\OpenSSL\bin\openssl.cfg

Open Command Prompt and type openssl. You should get a window like this:





This means that the setup is correct and complete. Else fix your windows PATH variable. Close this window.



Create a Root Certification Authority

Now we need to create a certificate for Root Certification Authority. Open Command Prompt and change location to demo folder using command:
cd C:\OpenSSL\demo

Create key as (location: C:\OpenSSL\demo):
openssl genrsa -out RootCA.key 4096

Use this key to create a Root Certificate using command:
openssl req -new -x509 -days 7300 -key RootCA.key -out RootCA.crt
The certificate expiration is set to 20 years (7300 days). Change to match your requirements.

You will have to enter details as:

The certificate name is the input entered against field: Common Name
Please note that if you press enter without entering a value, the default value (value displayed in []) will be used to create certificate. The certificate RootCA.crt will be created at location:
C:\OpenSSL\demo
This certificate will have to be installed in Trusted Root Certification Authority in any machine which the website is installed or used.



Create a Domain Certificate

Now we need to create a domain certificate. Create a folder contoso at location:
C:\OpenSSL\demo
Create a file csr_detail.cnf using the details below in contoso folder:
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req

[req_distinguished_name]
countryName = US
countryName_default = US
stateOrProvinceName = New York
stateOrProvinceName_default = NY
localityName = New York
localityName_default = New York
organizationalUnitName = Contoso Unit
organizationalUnitName_default = Contoso Unit
commonName = contoso.com
commonName_default = contoso.com
organizationName = Contoso
organizationName_default = Contoso
commonName_max  = 64

[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = www.contoso.com
DNS.2 = files.contoso.com
IP.1 = 0.0.0.0
Edit it to match your needs.

Open Command Prompt and change location to contoso folder using command:
cd C:\OpenSSL\demo\contoso 

Create a KEY for the certificate using the command:
openssl genrsa -out contoso.com.key 2048

Create a CSR file for the certificate using the command:
openssl req -new -out contoso.com.csr -key contoso.com.key -config csr_details.cnf
You will be asked to input fields as:
Press enter in each field to add default value already set from CNF file.


Create a certificate using the CNF file, KEY and the CSR file using the command:
openssl x509 -req -days 3650 -in contoso.com.csr -CA ..\RootCA.crt -CAkey ..\RootCA.key -set_serial 01  -extensions v3_req -extfile csr_details.cnf -out contoso.com.crt
This certificate will be created as contoso.com.crt at location:
C:\OpenSSL\demo\contoso

Now we need to create a PFX file so that this certificate can be imported in IIS. Use the following command:
openssl pkcs12 -export -out contoso.com.pfx -inkey contoso.com.key -in contoso.com.crt
You will be asked to enter a password (at least 4 characters) as:




Import this PFX file in IIS and use it in both the domains: www.contoso.com & files.contoso.com


Nov 7, 2016

Iterating over string array in template in SDL Tridion 2013 SP1

Now we can add any string array to template package and iterate over its members in Dreamweaver template. We need to serialize your array and then create package string item out of it as mentioned below:

var list = new[] { "aaa", "bbb", "ccc" };           

StringWriter stringWriter = new StringWriter();
XmlSerializer xmlSerializer = new XmlSerializer(list.GetType());
xmlSerializer.Serialize(stringWriter, list); 

package.PushItem("ItemName",
                  package.CreateStringItem(ContentType.StringArray, stringWriter.ToString()));

The DWT for this array will be as:
  <!-- TemplateBeginRepeat name="ItemName" -->
    <div>@@Value@@</div>
  <!-- TemplateEndRepeat -->

Fixing Chrome resolution issue

There is a very simple solution it fix the chrome resolution issue. Follow the steps below:
  1. Find the Chrome icon that you click on. It may be on the Windows taskbar, a shortcut on the desktop, or in the start menu or on the start screen.
  2. Right-click the icon and select properties from the context menu if the icon is on the desktop or start menu/screen.If it is on the taskbar, right-click Google Chrome in the context menu that opens up and select properties here.
  3. The 'Target' field should end like this afterwards: chrome.exe" /high-dpi-support=1 /force-device-scale-factor=1
Click OK to confirm the change.

Jun 13, 2016

Catching JavaScript Errors with window.onerror

First we need to override the handler as:

window.onerror = function (errorMsg, url, lineNumber) {
    console.log('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber);
}

We can add two more variables to get more information: column number and error object.

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
    console.log('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber 
    + ' Column: ' + column + ' StackTrace: ' +  errorObj);
}

Note: This will work only in the latest browsers.

Feb 8, 2016

Encrypt in SQL Server and Decrypt in C#

Recently, I had a requirement to fetch the encrypted string passed from SQL Server using function EncryptByPassPhrase (more details about this function here). This encrypted string was passed from a totally different setup to my ASP.Net web application.

My ASP.Net web Application required the decoded text. To do this I had to create a stored procedure which accepted the pass phrase and encrypted string as input and returned the decrypted string. The encrypted string type was VARBINARY. The stored procedure was:
CREATE PROCEDURE [dbo].sp_DecryptText 
    (@PassPhrase NVARCHAR(128), 
    @EncryptedText VARBINARY(MAX),
    @DecryptedText NVARCHAR(MAX) OUTPUT)
AS
BEGIN
    SET @DecryptedText = DECRYPTBYPASSPHRASE(@PassPhrase, @EncryptedText);
    RETURN
END
So I wrote a C# code to connect to stored procedure passing all the values as:
command.Parameters.AddWithValue("@PassPhrase", PassPhrase);
command.Parameters.Add("@EncryptedText", SqlDbType.VarBinary, 8000).Value = Encoding.Unicode.GetBytes(encryptedString);
command.Parameters.Add("@DecryptedText", SqlDbType.NVarChar, -1).Direction = ParameterDirection.Output;
But this did not work as the encryptedString was already in hexadecimal format and converting it to bytes resulted in a totally different string.

To get the stored procedure working, I converted the encryptedString to hexadecimal before passing it to the stored procedure by writing a separate function ParseHexString as:
static byte[] ParseHexString(string value)
{
    if (string.IsNullOrEmpty(value)) return null;
    if (1 == (1 & value.Length)) throw new ArgumentException("Invalid length for a hex string.", "value");

    int startIndex = 0;
    int length = value.Length;
    char[] input = value.ToCharArray();
    if ('0' == input[0] && 'x' == input[1])
    {
        if (2 == length) return null;
        startIndex = 2;
        length -= 2;
    }

    Func<char, byte> charToWord = c =>
    {
        if ('0' <= c && c <= '9') return (byte)(c - '0');
        if ('A' <= c && c <= 'F') return (byte)(10 + c - 'A');
        if ('a' <= c && c <= 'f') return (byte)(10 + c - 'a');
        throw new ArgumentException("Invalid character for a hex string.", "value");
    };

    byte[] result = new byte[length >> 1];
    for (int index = 0, i = startIndex; index < result.Length; index++, i += 2)
    {
        byte w1 = charToWord(input[i]);
        byte w2 = charToWord(input[i + 1]);
        result[index] = (byte)((w1 << 4) + w2);
    }

    return result;
}

So my call to stored procedure changed to:
command.Parameters.AddWithValue("@PassPhrase", PassPhrase);
command.Parameters.Add("@EncryptedText", SqlDbType.VarBinary, 8000).Value = ParseHexString(encryptedString);
command.Parameters.Add("@DecryptedText", SqlDbType.NVarChar, -1).Direction = ParameterDirection.Output;
And the output was correct and in the right format!!


Oct 31, 2015

Change Creation Date of file to Modified Date using PowerShell

Use the following PowerShell command to change the Creation Date to the Modified Date of all files in a folder.

Get-ChildItem -recurse -filter *.JPG | % { $_.CreationTime = $_.LastWriteTime }

Oct 8, 2015

Rename all files replacing a text using PowerShell

Let's say you have a number of files at location C:\demo with text "OldValue" in it. And you want to replace text "OldValue" to "NewValue" in all files. To do that follow the steps below:

  1. Open Windows PowerShell.
  2. Navigate to location C:\demo
  3. Run the following Windows PowerShell command: 
    Get-ChildItem -Filter "*OldValue*" -Recurse | Rename-Item -NewName {$_.name -replace 'OldValue','NewValue' }
  4. All files will be renamed.

  • The command Get-ChildItem -Filter "*OldValue*" finds all files with the string "OldValue" anywhere in the name.
  • Get-ChildItem searches recursively through all subfolders.
  • | (the pipe character) instructs Windows PowerShell to take each item (object) found with the first command (Get-ChildItem) and pass it to the second command (Rename-Item)
  • Rename-Item renames files and other objects.
  • {$_.name -replace 'OldValue','NewValue' } instructs Rename-Item to find the string "OldValue" in the file name and replace it with "NewValue"