Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

AES Encrypted SSO – C# to PHP

Posted on March 25, 2013October 26, 2015 By David Kittell
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="csharp.aspx.cs" Inherits="csharp" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>CSharp to PHP</title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divDebugInfo" runat="server" visible="false">

    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

#region AES Pass-Through - Start
using System.Security.Cryptography;
using System.Text;
using System.IO;
#endregion AES Pass-Through - Stop

public partial class csharp : System.Web.UI.Page
{
	public string sDateTime = "";
	public string sep = "rn";
	public string strUserName = "";

	protected void Page_Load(object sender, EventArgs e)
	{
		//Disable Cache
		Response.Cache.SetCacheability(HttpCacheability.NoCache);

		#region Check User Login Status - Start
		//try
		//{
		//	if (IsLoggedIn())
		//	{
		//		// If logged in use that username
		//		strUserName = UserName();
		//	}
		//	else
		//	{
		//		// if not logged in redirect to login page
		//		Response.Redirect("/login");
		//	}
		//}
		//catch (Exception ee)
		//{
		//	Response.Redirect("/login");
		//}

		//DEBUG/TESTING PURPOSES ONLY
		strUserName = "dkittell";
		#endregion Check User Login Status - Stop

		System.DateTime localtime = DateTime.Now;
		//localtime = DateTime.Parse("3/18/2012 4:39:22 PM");
		localtime = localtime.ToUniversalTime();
		sDateTime = localtime.ToString();

		const string sKy = "Fw58xNju9c0SUrfsPGm2OO0X68LYlIXc"; //32 chr shared ascii string (32 * 8 = 256 bit)
		const string sIV = "Qqh64ul174gj948HT5q9cHJLf2BE2S03"; //32 chr shared ascii string (32 * 8 = 256 bit)

		var sTextVal = strUserName + sep + sDateTime + sep + "Kittell" + sep + Md5Encode(strUserName + sDateTime);

		var eText = EncryptRJ256(sKy, sIV, sTextVal);
		var dText = DecryptRJ256(sKy, sIV, eText);

		divDebugInfo.InnerHtml = "<p>" + "key: " + sKy + "</p>" +
			"<p>" + " iv: " + sIV + "</p>" +
			"<p>" + "txt: " + sTextVal + "</p>" +
			"<p>" + "Encrypted: " + eText + "</p>" +
			"<p>" + "Decrypted: " + dText + "</p>" +
			"<p>" + "URL: <a href='php.php?key=" + eText + "'>php.php?key=" + eText + "</a></p>";

		divDebugInfo.Visible = true;
	}

	public string DecryptRJ256(string prm_key, string prm_iv, string prm_text_to_decrypt)
	{

		var sEncryptedString = prm_text_to_decrypt;

		var myRijndael = new RijndaelManaged()
		{
			Padding = PaddingMode.Zeros,
			Mode = CipherMode.CBC,
			KeySize = 256,
			BlockSize = 256
		};

		var key = Encoding.ASCII.GetBytes(prm_key);
		var IV = Encoding.ASCII.GetBytes(prm_iv);

		var decryptor = myRijndael.CreateDecryptor(key, IV);

		var sEncrypted = Convert.FromBase64String(sEncryptedString);

		var fromEncrypt = new byte[sEncrypted.Length];

		var msDecrypt = new MemoryStream(sEncrypted);
		var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

		csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

		return (Encoding.ASCII.GetString(fromEncrypt));
	}

	public string EncryptRJ256(string prm_key, string prm_iv, string prm_text_to_encrypt)
	{

		var sToEncrypt = prm_text_to_encrypt;

		var myRijndael = new RijndaelManaged()
		{
			Padding = PaddingMode.Zeros,
			Mode = CipherMode.CBC,
			KeySize = 256,
			BlockSize = 256
		};

		var key = Encoding.ASCII.GetBytes(prm_key);
		var IV = Encoding.ASCII.GetBytes(prm_iv);

		var encryptor = myRijndael.CreateEncryptor(key, IV);

		var msEncrypt = new MemoryStream();
		var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

		var toEncrypt = Encoding.ASCII.GetBytes(sToEncrypt);

		csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
		csEncrypt.FlushFinalBlock();

		var encrypted = msEncrypt.ToArray();

		return (Convert.ToBase64String(encrypted));
	}

	public string Md5Encode(string str)
	{
		byte[] unicodeText = System.Text.Encoding.UTF8.GetBytes(str);
		// Now that we have a byte array we can ask the CSP to hash it
		MD5 md5 = new MD5CryptoServiceProvider();
		byte[] result = md5.ComputeHash(unicodeText);
		return Base64Encode(result);
	}

	public string Base64Encode(byte[] encbuff)
	{
		return Convert.ToBase64String(encbuff);
	}
	public byte[] Base64Decode(string str)
	{
		return Convert.FromBase64String(str);
	}


}

// Debug - Show all errors - start
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Debug - Show all errors - stop

// SSO Pass-Through Start
$ky = 'Fw58xNju9c0SUrfsPGm2OO0X68LYlIXc'; // 32 * 8 = 256 bit key
$iv = 'Qqh64ul174gj948HT5q9cHJLf2BE2S03'; // 32 * 8 = 256 bit iv

$From_Source = "";

try {
    // Try to pull the key from the URL
    $From_Source = $_GET['key'];
}
catch (Exception $e) {
    // If we are not passing a key we don't want to show exception as we will simply show the login form to the user.
     echo 'Caught exception: ',  $e->getMessage(), "n";
}

function decryptRJ256($key,$iv,$string_to_decrypt)
{
    $string_to_decrypt = base64_decode($string_to_decrypt);
    $rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
    $rtn = rtrim($rtn, "4");
    return($rtn);
}

function encryptRJ256($key,$iv,$string_to_encrypt)
{
    $rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
    $rtn = base64_encode($rtn);
    return($rtn);
}

echo $From_Source;

if ($From_Source != "")
    {
        // If we are not passing a key we will simply show the login form to the user.

        echo $From_Source;

        //$etext = encryptRJ256($ky, $iv, $text);
        //$dtext = decryptRJ256($ky, $iv, $etext);
        $vtext = decryptRJ256($ky, $iv, $From_Source);

        $pieces = explode("rn", $vtext);
        $decryptedusername = $pieces[0];
        $decrypteddatetime = $pieces[1];
        $decryptedname = $pieces[2];

        if ($decryptedname != "Kittell"){
            // SSO Key was passed but did not come from Source so we will redirect to the main site
            echo "Bad Login Attempt!";
            //echo '<meta http-equiv="refresh" content="0;url=http://www.kittell.net/">';
            exit;
        }

        // Get Current DateTime then convert it to UTC - Start
        // By converting to UTC we will reduce the issues of servers being in different locations.
        $UTC = new DateTimeZone("UTC");
        $date = new DateTime(date("n/j/Y g:i:s A"));
        $date->setTimezone( $UTC );
        $serverdatetime =  $date->format('n/j/Y g:i:s A');
        // Get Current DateTime then convert it to UTC - Stop

        // Get Date and Time pieces from the server date/time stamp in order to compare
        $pieces = explode(" ", $serverdatetime);
        $serverdate = $pieces[0];
        $servertime = $pieces[1];

        // Get Date and Time pieces from the decrypted date/time stamp in order to compare
        $pieces = explode(" ",  $decrypteddatetime);
        $decrypteddate = $pieces[0];
        $decryptedtime = $pieces[1];

        //echo "<P>" . $servertime;
        //echo "<P>" . $decryptedtime;

        if ($serverdate == $decrypteddate)
            {
                // We have matched the date of the server to the decrypted date, now we look at the time to match
                //  echo "<p>Same Date";

                // Split decrypted time into hour and minue values
                $pieces = explode(":",  $decryptedtime);
                $decryptedtime_hour = $pieces[0];
                $decryptedtime_minute = $pieces[1];
                //  echo "<P>" . $decryptedtime_hour;
                //  echo "<P>" . $decryptedtime_minute;

                // Split server time into hour and minue values
                $pieces = explode(":", $servertime);
                $servertime_hour = $pieces[0];
                $servertime_minute = $pieces[1];
                //  echo "<P>" . $servertime_hour;
                //  echo "<P>" . $servertime_minute;

                if ($servertime_hour == $decryptedtime_hour)
                    {
                        // We have matched the hour of the server to the decrypted hour, now we look at the minutes to match set guide lines
                        //echo "<p>Same Hour";
                        switch ((int)$servertime_minute) {
                            case (int)$decryptedtime_minute:
                            case (int)$decryptedtime_minute -1:
                            case (int)$decryptedtime_minute -2:
                            case (int)$decryptedtime_minute +1:
                            case (int)$decryptedtime_minute +2:
                                // If the server time is less than or greater than the decrypted time by up to two minutes we consider it to be a valid pass-thru

                                //echo "<br>Good Time";
                                //echo $decryptedname  . "<p>";

                                // In order for this pass-thru the user has to exist on Source and WordPress
                                // WordPress functions require a password to be passed so all WordPress SSO accounts will have a default password set, if this password is changed the SSO pass-thru will not work.
                                // Default WordPress user password: w7|IwHe2/b[UX^m

                                $password = "w7|IwHe2/b[UX^m";

                                // WordPress function pieces: http://codex.wordpress.org/Function_Reference/wp_set_auth_cookie
                                $remember = true;
                                $secure = "";

                                    echo "<br>Username: " . $decryptedusername; // piece1
                                    echo "<br>DateTime: " . $decrypteddatetime; // piece2

                    //          wp_set_auth_cookie($decryptedusername, $remember, $secure);
                                //echo '<meta http-equiv="refresh" content="0;url=http://www.kittell.net/">';
                            break;
                            default:
                                // SSO Pass-thru process did not pass validation
                                echo "Bad Login Attempt!";
                            //  echo '<meta http-equiv="refresh" content="0;url=http://www.kittell.net/">';
                                exit;
                            break;
                        } // End switch statement

                        //echo "<HR>orignal string: $text";
                        //echo "<HR>encrypted in php: $etext";
                        //echo "<HR>decrypted in php: $dtext";
                        //echo "<HR>encrypted in vb: $From_Source";
                        //echo "<br>Decrypted C# String: $vtext";
                    }
                else
                    {
                        // We have not matched the hour of the server to the decrypted hour
                        // SSO Pass-thru process did not pass validation
                        echo "Bad Login Attempt!";
                        //echo '<meta http-equiv="refresh" content="0;url=http://www.kittell.net/">';
                        exit;
                    }
            }
        else
            {
                // We have not matched the date of the server to the decrypted date
                // SSO Pass-thru process did not pass validation
                echo "Bad Login Attempt!";
            //  echo '<meta http-equiv="refresh" content="0;url=http://www.kittell.net/">';
                exit;
            }
    }
// SSO Pass-Through Stop

Originally Posted on March 25, 2013
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code CSharp PHP

Post navigation

Previous post
Next post

Related Posts

PowerShell – UNIX SED Equivalent – Change Text In File

Posted on March 3, 2016March 3, 2016

Unix SED command is very useful to make changes to a configuration file when you know what the default values are, below is a way to do a SED-like text change in PowerShell (Get-Content c:\temp\test.txt).replace(‘[MYID]’, ‘MyValue’) | Set-Content c:\temp\test.txt Example: TeamCity Build Agent Configuration file needs updated so it knows…

Read More

Ektron Find Replace In Sitemap

Posted on October 23, 2013October 26, 2015

This script will search and replace sitemap links/titles/etc set xact_abort on declare @currurl nvarchar(500) declare @newurl nvarchar(500) declare @search nvarchar(500) declare @replace varchar(500) set @search = ” –string to find set @replace = ” –replacement string declare @pos int declare @id bigint declare @ol int declare @lang int begin tran…

Read More

Ping Trace

Posted on July 18, 2013October 26, 2015

Set objShell = CreateObject("WScript.Shell") objShell.Run "%COMSPEC% /k ping 8.8.8.8",,True objShell.Run "%COMSPEC% /k tracert 8.8.8.8" Originally Posted on July 18, 2013Last Updated on October 26, 2015 All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • Open On Screen Keyboard (OSK)
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes