Sunday, 16 June 2013

Encryption and Decryption of Password using Rijndael algorithm



MyEncryptor m = new MyEncryptor("");

//Encrypt the Password
string encrptString = m.Encrypt(txtPassword.Text.Trim());

//Decrypt the password.
string decryptString = m.Decrypt(dbpassword);

if (decryptString == password)
{
//Password Match
}Else{
//Failure

}



/* MyEncryptor.cs */


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class MyEncryptor
    {
        // Internal value of the phrase used to generate the secret key
        private string _Phrase = "";
        //contains input file path and name
        private string _inputFile = "";
        //contains output file path and name
        private string _outputFile = "";
        enum TransformType { ENCRYPT = 0, DECRYPT = 1 }
        /// <value>Set the phrase used to generate the secret key.</value>
        public string Phrase
        {
            set
            {
                this._Phrase = value;
                this.GenerateKey(this._Phrase);
            }
        }

        // Internal initialization vector value to
        // encrypt/decrypt the first block
        private byte[] _IV;

        // Internal secret key value
        private byte[] _Key;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="SecretPhrase">Secret phrase to generate key</param>
        public MyEncryptor(string SecretPhrase)
        {
            this.Phrase = SecretPhrase;
        }

        /// <summary>
        /// Encrypt the given value with the Rijndael algorithm.
        /// </summary>
        /// <param name="EncryptValue">Value to encrypt</param>
        /// <returns>Encrypted value. </returns>
        public string Encrypt(string EncryptValue)
        {
            try
            {
                if (EncryptValue.Length > 0)
                {
                    // Write the encrypted value into memory
                    byte[] input = Encoding.UTF8.GetBytes(EncryptValue);

                    // Retrieve the encrypted value and return it
                    return (Convert.ToBase64String(Transform(input, TransformType.ENCRYPT)));

                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Decrypt the given value with the Rijndael algorithm.
        /// </summary>
        /// <param name="DecryptValue">Value to decrypt</param>
        /// <returns>Decrypted value. </returns>
        public string Decrypt(string DecryptValue)
        {

            try
            {
                if (DecryptValue.Length > 0)
                {
                    // Write the encrypted value into memory                    
                    byte[] input = Convert.FromBase64String(DecryptValue);

                    // Retrieve the decrypted value and return it
                    return (Encoding.UTF8.GetString(Transform(input, TransformType.DECRYPT)));

                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Encrypt the given value with the Rijndael algorithm.
        /// </summary>
        /// <param name="EncryptValue">Value to encrypt</param>
        /// <returns>Encrypted value. </returns>
        public void Encrypt(string InputFile, string OutputFile)
        {

            try
            {
                if ((InputFile != null) && (InputFile.Length > 0))
                {
                    _inputFile = InputFile;
                }
                if ((OutputFile != null) && (OutputFile.Length > 0))
                {
                    _outputFile = OutputFile;
                }
                Transform(null, TransformType.ENCRYPT);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Decrypt the given value with the Rijndael algorithm.
        /// </summary>
        /// <param name="DecryptValue">Value to decrypt</param>
        /// <returns>Decrypted value. </returns>
        public void Decrypt(string InputFile, string OutputFile)
        {

            try
            {
                if ((InputFile != null) && (InputFile.Length > 0))
                {
                    _inputFile = InputFile;
                }
                if ((OutputFile != null) && (OutputFile.Length > 0))
                {
                    _outputFile = OutputFile;
                }
                Transform(null, TransformType.DECRYPT);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /*****************************************************************
         * Generate an encryption key based on the given phrase.  The
         * phrase is hashed to create a unique 32 character (256-bit)
         * value, of which 24 characters (192 bit) are used for the
         * key and the remaining 8 are used for the initialization
         * vector (IV).
         *
         * Parameters:  SecretPhrase - phrase to generate the key and
         * IV from.
         *
         * Return Val:  None 
         ***************************************************************/
        private void GenerateKey(string SecretPhrase)
        {
            // Initialize internal values
            this._Key = new byte[24];
            this._IV = new byte[16];

            // Perform a hash operation using the phrase.  This will
            // generate a unique 32 character value to be used as the key.
            byte[] bytePhrase = Encoding.ASCII.GetBytes(SecretPhrase);
            SHA384Managed sha384 = new SHA384Managed();
            sha384.ComputeHash(bytePhrase);
            byte[] result = sha384.Hash;

            // Transfer the first 24 characters of the hashed value to the key
            // and the remaining 8 characters to the intialization vector.
            for (int loop = 0; loop < 24; loop++) this._Key[loop] = result[loop];
            for (int loop = 24; loop < 40; loop++) this._IV[loop - 24] = result[loop];
        }

        /*****************************************************************
         * Transform one form to anoter based on CryptoTransform
         * It is used to encrypt to decrypt as well as decrypt to encrypt
         * Parameters:  input [byte array] - which needs to be transform
         *              transformType - encrypt/decrypt transform
         *
         * Return Val:  byte array - transformed value.
         ***************************************************************/
        private byte[] Transform(byte[] input, TransformType transformType)
        {
            CryptoStream cryptoStream = null;      // Stream used to encrypt
            RijndaelManaged rijndael = null;        // Rijndael provider
            ICryptoTransform rijndaelTransform = null;// Encrypting object           
            FileStream fsIn = null;                 //input file
            FileStream fsOut = null;                //output file
            MemoryStream memStream = null;          // Stream to contain data
            try
            {
                // Create the crypto objects
                rijndael = new RijndaelManaged();
                rijndael.Key = this._Key;
                rijndael.IV = this._IV;
                if (transformType == TransformType.ENCRYPT)
                {
                    rijndaelTransform = rijndael.CreateEncryptor();
                }
                else
                {
                    rijndaelTransform = rijndael.CreateDecryptor();
                }

                if ((input != null) && (input.Length > 0))
                {
                    memStream = new MemoryStream();
                    cryptoStream = new CryptoStream(
                         memStream, rijndaelTransform, CryptoStreamMode.Write);

                    cryptoStream.Write(input, 0, input.Length);

                    cryptoStream.FlushFinalBlock();

                    return memStream.ToArray();

                }
                else if ((_inputFile.Length > 0) && (_outputFile.Length > 0))
                {
                    // First we are going to open the file streams
                    fsIn = new FileStream(_inputFile,
                                FileMode.Open, FileAccess.Read);
                    fsOut = new FileStream(_outputFile,
                                FileMode.OpenOrCreate, FileAccess.Write);

                    cryptoStream = new CryptoStream(
                        fsOut, rijndaelTransform, CryptoStreamMode.Write);

                    // Now will will initialize a buffer and will be
                    // processing the input file in chunks.
                    // This is done to avoid reading the whole file (which can be
                    // huge) into memory.
                    int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int bytesRead;
                    do
                    {
                        // read a chunk of data from the input file
                        bytesRead = fsIn.Read(buffer, 0, bufferLen);
                        // Encrypt it
                        cryptoStream.Write(buffer, 0, bytesRead);

                    } while (bytesRead != 0);

                    cryptoStream.FlushFinalBlock();
                }
                return null;

            }
            catch (CryptographicException)
            {
                throw new CryptographicException("Password is invalid. Please verify once again.");
            }
            finally
            {
                if (rijndael != null) rijndael.Clear();
                if (rijndaelTransform != null) rijndaelTransform.Dispose();
                if (cryptoStream != null) cryptoStream.Close();
                if (memStream != null) memStream.Close();
                if (fsOut != null) fsOut.Close();
                if (fsIn != null) fsIn.Close();
            }
        }

    }



Friday, 17 May 2013

pure Html Registration Page with Validations


<!DOCTYPE html>
<html>
<head>
    <title>Basic usage</title>
    <link href="Styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
    <link href="Styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
    <link href="Styles/examples-offline.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .txtPhoneWidth
        {
            width: 37px;
        }
        .txtPhoneWidth2
        {
            width: 42px;
        }
        .txtExpWidth
        {
            width: 60px;
        }
        .txtExpWidth2
        {
            width: 70px;
        }
           
    </style>
    <script type="text/javascript">
        /***********************************************
        * Drop Down Date select script- by JavaScriptKit.com
        * This notice MUST stay intact for use
        * Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
        ***********************************************/

        var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

        function populatedropdown(monthfield, yearfield) {
            var today = new Date()          
            var monthfield = document.getElementById(monthfield)
            var yearfield = document.getElementById(yearfield)
           
            for (var m = 0; m < 12; m++)
                monthfield.options[m] = new Option(monthtext[m], monthtext[m])
            monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
            var thisyear = today.getFullYear()
            for (var y = 0; y < 40; y++) {
                yearfield.options[y] = new Option(thisyear, thisyear)
                thisyear += 1
            }
            yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year



        }
        function Validation() {
            debugger;
            LName = document.getElementById("txtLastName");
            CompanyNum = document.getElementById("CompanyNum");
            TransType = document.getElementById("TransType");
            CardNum = document.getElementById("CardNum");
            ExpMonth = document.getElementById("ExpMonth");
            ExpYear = document.getElementById("ExpYear");
            Member = document.getElementById("Member");
            TypeCredit = document.getElementById("TypeCredit");
            Payments = document.getElementById("Payments");
            Amount = document.getElementById("Amount");
            Currency = document.getElementById("Currency");
            CVV = document.getElementById("CVV");
            Email = document.getElementById("Email");
            var emailRegexStr = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            var isvalid = emailRegexStr.test(Email.value);
            if (!isvalid) {
                alert('Invalid email address!');
                document.getElementById("Email").focus();
                return false;
            }

            BillingAddress1 = document.getElementById("BillingAddress1");
            BillingCity = document.getElementById("BillingCity");
            BillingZipCode = document.getElementById("BillingZipCode");
            BillingState = document.getElementById("BillingState");
            BillingCountry = document.getElementById("BillingCountry");
            PhoneNum0 = document.getElementById("txtPhoneNum0");
            PhoneNum1 = document.getElementById("txtPhoneNum1");
            PhoneNum2 = document.getElementById("txtPhoneNum2");
            if (PhoneNum0.value != "" && PhoneNum1.value != "" && PhoneNum2.value != "") {
                PhoneNumber = PhoneNum0.value + "" + PhoneNum1.value + "" + PhoneNum2.value;
            }
            else {
                alert("* Indicate Mandiatory Field Please Fill all the details");
                return false;
            }

            if (LName.value != "" && CompanyNum.value != "" && TransType.value != "" && CardNum.value != "" && ExpMonth.value != "" && ExpYear.value != "" && Member.value != "" && TypeCredit.value != "" && Payments.value != "" && Amount.value != "" && Currency.value != "" && CVV.value != "" && Email.value != "" && PhoneNumber.value != "" && BillingAddress1.value != "" && BillingCity.value != "" && BillingZipCode.value != "" && BillingState.value != "" && BillingCountry.value != "") {
                alert("Success");
                return true;
                debugger;
            }
            else {
                alert("* Indicate Mandiatory Field Please Fill all the details");
                return false;
            }


        }


   

</script>
</head>
<body>
    <form action="https://process.netpay-intl.com/member/remote_charge.asp" method="post"
    name="formName1" onsubmit="alert('hello')">
    <script type="text/javascript">

        //populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
        window.onload = function () {
            populatedropdown("ExpMonth", "ExpYear")

        }
    </script>
    <div id="example" class="k-content" style="height: 550px">
        <div style="width: 100%; text-align: center">
            <label style="font-size: xx-large; font-weight: bold; color: #1c3360">
                Net Pay GateWay</label>
        </div>
        <table style="width: 100%; margin-top: 50px">
            <tr style="margin-top: 10px">
                <td style="width: 50%" align="center">
                    <table cellspacing="2px" cellpadding="4px">
                        <tr>
                            <td align="left">
                                First Name
                            </td>
                            <td align="left">
                                <input type="text" id="txtFirstName" title="Enter your first name" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Last Name<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="txtLastName" title="Enter your last Name" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Email<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="Email" title="Enter Your Email" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Phone Number<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <table>
                                    <tr>
                                        <td>
                                            <input type="text" id="txtPhoneNum0" title="Enter Your Phone Number" maxlength="3"
                                                class="txtPhoneWidth" />
                                        </td>
                                        <td>
                                            <input type="text" id="txtPhoneNum1" title="Enter Your Phone Number" maxlength="3"
                                                class="txtPhoneWidth" />
                                        </td>
                                        <td>
                                            <input type="text" id="txtPhoneNum2" title="Enter Your Phone Number" maxlength="4"
                                                class="txtPhoneWidth2" />
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <b>Billing Address</b>
                            </td>
                            <td>
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Address<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input id="BillingAddress1" title="Enter address" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                City&nbsp;Name<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <div id="CityName" class="ui-widget">
                                    <label for="Cities">
                                    </label>
                                    <input id="BillingCity" title="Enter City" />
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                State<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <div id="stateName" class="ui-widget">
                                    <label for="State">
                                    </label>
                                    <input id="BillingState" title="Enter State" />
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Country<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <div id="Country" class="ui-widget">
                                    <label for="Country">
                                    </label>
                                    <input id="BillingCountry" title="Enter Country" maxlength="2">
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Pincode<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="BillingZipCode" title="Enter pincode" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Amount<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="Amount" title="Enter Amount" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Currency<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <select id="Currency" title="Select Currency">
                                    <option>Select</option>
                                    <option value="0">ILS (Israel New Shekel)</option>
                                    <option value="1">USD (US Dollar)</option>
                                    <option value="2">EUR (Euro)</option>
                                    <option value="3">GBP (UK Pound Sterling)</option>
                                    <option value="4">AUD (Australian Dollar)</option>
                                    <option value="5">CAD (Canadian Dollar)</option>
                                    <option value="6">JPY (Japanese Yen)</option>
                                    <option value="7">NOK (Norwegian Krone)</option>
                                    <option value="8">PLN (Polski zloty)</option>
                                    <option value="9">MXN (Mexican Peso)</option>
                                    <option value="10">ZAR (South African Rand)</option>
                                    <option value="11">RUB (Russian Ruble </option>
                                    <option value="12">TRY (Turkish lira)</option>
                                    <option value="13">CHF (Swiss franc) </option>
                                    <option value="14">INR (Indian rupee)</option>
                                    <option value="15">DKK (Danish krone)</option>
                                    <option value="16">SEK (Swedish krona)</option>
                                    <option value="17">CNY (Chinese yuan)</option>
                                    <option value="18">HUF (Hungarian forint)</option>
                                    <option value="19">NZD (New Zealand dollar) </option>
                                    <option value="20">HKD (Hong Kong dollar)</option>
                                    <option value="21">KRW (South Korean won) </option>
                                </select>
                            </td>
                        </tr>
                    </table>
                </td>
                <td style="width: 50%;" valign="vertical" align="left">
                    <table cellspacing="2px" cellpadding="4px">
                        <tr>
                            <td colspan="2">
                                <b>Credit Card Details</b>
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Name on Credit Card <span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="Member" title="Enter Name on Credit Card" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Card Number<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="CardNum" title="Enter Credit Card Number" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Expiration <span style="color: Red">*</span>
                            </td>
                            <td>
                                <table>
                                    <tr>
                                        <td>
                                            <select id="ExpMonth" class="txtExpWidth">
                                            </select>
                                        </td>
                                        <td>
                                            <select id="ExpYear" class="txtExpWidth2">
                                            </select>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td align="left">
                                Enter CVV<span style="color: Red">*</span>
                            </td>
                            <td align="left">
                                <input type="text" id="CVV" title="Enter CVV Number" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                            <td align="right">
                                <input class="offline-button" type="submit" value="submit" onclick="return Validation();">
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <input type="hidden" name="CompanyNum" value="3409473" id="CompanyNum" />
        <input type="hidden" name="TransType" value="1" id="TransType" />
        <input type="hidden" name="TypeCredit" value="1" id="TypeCredit" />
        <input type="hidden" name="Payments" value="1" id="Payments" />
        <input type="hidden" name="PhoneNumber" id="PhoneNumber" />
        <style scoped>
            #example h2
            {
                font-weight: normal;
            }
            #email-settings
            {
                height: 135px;
                width: 395px;
                margin: 30px auto;
                padding: 110px 0 0 30px;
                background: url('../../content/web/datepicker/mailSettings.png') transparent no-repeat 0 0;
            }
        </style>
    </div>
    </form>
</body>
</html>