Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Security on the Web by Advanced Encryption Standard (AES) and Security Assertion Markup Language (SAML)

4.99/5 (27 votes)
3 Apr 2019CPOL13 min read 82.2K   760  
Best approach for having more secure channel to transfer user information throughout the web

Cryptography

Most of the issues on the web are related to security matters and because of keeping and transferring sensitive data in the web. So we must provide a secure system on it. The most popular and practical way to establish a secure connection in the web is cryptography techniques. Cryptography techniques are the process of encryption and decryption data to keep data secure. For example, in the below figure, Bob wants to send data to Alice. This data is known as message and input parameter to cryptography process. Then specific key with encryption function will be added to this message and produce cipher text which is our encrypted message so this message goes through the network where hackers are waiting to rob this data.

Image 1

On the other stage, Alice waits to receive Bob`s message and on that side, there is decryption function which uses the same secret key to decrypt message. This secret key is absolutely similar to a key from Bob's side. So decryption function with the same secret key and cipher text (encrypted key) will produce decrypted message for Alice and finally Alice will receive Bob`s message. This process is known as Symmetric Encryption.

The biggest issue in this process is to provide a strong and complex key. Because encryption and decryption algorithms are available on the internet and use almost similar steps and functions to encrypt data and change these algorithms is useless as hackers can find them easily. So we must concentrate on producing power secret key to keep safe confidential data.

  1. Cryptography is tremendous and Fabulous tools for any security issue.
  2. But Cryptography is not suitable for the naive user to do action to hurt themselves especially for social attackers.
  3. Cryptography needs to innovate new ways, as using old encryption systems is as bad as not using it.
  4. If Cryptography is implemented incorrectly does not except meet your requirement correctly.
Some Secure Communication Solutions
  1. Web Traffic: HTTPS -> Secure Socket Layer (SSL/TLS)
  2. Wireless Traffic: GSM: 802.11 Or WPA2: Bluetooth
  3. Encryption File on Disk

Advanced Encryption Standard (AES)

AES is one of the cryptography techniques which use the same secret key and is on the Rijndael cipher algorithm. AES is based on substitution and permutation functions and uses complicated ways to produce a strong and almost unbreakable key which is our aim in order to transmit our sensitive data through the network.

At the first step, AES expands key with the 128 bits length to more than ten keys where each of these keys have 128 bits length, the number of produced key build variant cycles. Message as input parameter will be mixed with these keys. AES just uses “AddRoundKey” function in the K0 and in the Kn uses “SubBytes”, “Shiftrows” and "AddRoundKey” and in the AES uses in the K2 to Kn-1 all of four functions “AddRoundKey”, “SubBytes”, “Shiftrows” and "AddRoundKey”. Eventually, message or plain text passes these complicated functions and will be converted to encrypted message or cipher text.

AES uses this pattern inversely to produce same message from encrypted message. AES converts message text and key to four by four matrix, because of working by matrix form is more easier than original form. Look at the below picture for having a more clear imagination of what happens inside AES algorithm.

Image 2

AddRoundKey

This function mixes Ki,j and Mi,j by XOR function. It means AES picks up ith rowand jth column from both message and key and applies XOR function for these coincident row and column and produces Ci,j. In this below picture, XOR will be applied between blue key and red message to produce orange cypher.

Image 3

SubBytes

This function finds substitution for Mi,j from substitution table with specific pattern and steps and replaces this new as a M~i,j. It means AES picks up ith row and jth column from message and applies substitution function for each row and column of message matrix and produces cypher matrix Ci,j.

Image 4

MixColumns

There is a fix matrix as C which will be affecting on the message matrix. At the first step, it does not change first row but it shifts second row to the left and it shifts to the left for the third row besides applies XOR function for that.

Image 5

Shift Rows

This function picks up message matrix and does not change the first row of this matrix, after that for the second row, shift one cell so that M1,0 will be replaced to M1,3. For the second row, shift two and for the third one, shift three.

Image 6

I have illustrated the below picture as a more deep through operation inside AES. There are DES and 3DES algorithms which are almost similar to AES, exception is 3DES is 168 and it has some bits more than AES, but it just uses permutation function for generating key while AES uses both permutation and substitution function and takes less time rather than 3DES.

Image 7

My Solution to Have More Security on the Web

I want to issue a solution with authentication and authorization parts for identifying users. Authentication provides us to know if user`s claim is correct or not by getting username and password. There is a solution to make this part as two step verification, first by getting a password and second by biometric signs. In this state, if someone steals user's password, the hacker cannot go to this user`s profile.

The next part is authorization which is related to permission management and determines if specific role has right to access and see specific section or not. For example here (in an EHealth Care System), the doctor has permission to access his or her patient's health information and read or write EHR.

The third section is cryptography techniques (AES). As I have mentioned above, AES uses a different function to encrypt data from hackers. So data in database can be saved as encrypted text instead of plain text to increase security issues.

Image 8

More Description On My Solution

My solution is to use biometric signs and mix this key to the secret key in order to produce more strong and secure key in AES. This biometric key can be extracted from fingerprint or cornea signs. Nowadays, capturing fingerprint is possible by mobile phone such as iphone and this data can be converted to second key matrix and mixing it with secret key we have strong key. These signs are available with us always and we will not forget them and hackers cannot get them so it is a good solution to keep data confidentiality.

Image 9

How to Use and Implement the Code

At first, open Visual Studio 2013 -> File (Menu) -> New Project -> ASP.NET MVC -> Empty Controller -> Add New Controller

Image 10

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace WebSecurity.Controllers
{
    public class AESController : Controller
    {
        //
        // GET: /AES/

        public ActionResult Index()
        {
            ViewData["Encrypted"] = TempData["TEncrypted"];
            ViewData["Decrypted"] = TempData["TDecrypted"];
            return View();
        }

        //txtforEN is PlainText
        //Key is Public Secret Key 
        [HttpPost]
        public ActionResult Encryption(string Text, string Key)
        {
            // Convert String to Byte

            byte[] MsgBytes = Encoding.UTF8.GetBytes(Text);
            byte[] KeyBytes = Encoding.UTF8.GetBytes(Key);

            // Hash the password with SHA256
            //Secure Hash Algorithm
            //Operation And, Xor, Rot,Add (mod 232),Or, Shr
            //block size 1024
            //Rounds 80
            //rotation operator , rotates point1 to point2 by theta1=> p2=rot(t1)p1
            //SHR shift to right
            KeyBytes = SHA256.Create().ComputeHash(KeyBytes);

            byte[] bytesEncrypted = AES_Encryption(MsgBytes, KeyBytes);

            string encryptionText = Convert.ToBase64String(bytesEncrypted);

            TempData["TEncrypted"] = encryptionText;
            return RedirectToAction("Index");
        }

        public byte[] AES_Encryption(byte[] Msg, byte[] Key)
        {
            byte[] encryptedBytes = null;

            //salt is generated randomly as an additional number to 
            //hash password or message in order o dictionary attack
            //against pre computed rainbow table
            //dictionary attack is a systematic way to test 
            //all of possibilities words in dictionary weather or not is true?
            //to find decryption key
            //rainbow table is precomputed key for cracking password
            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.  == 16 bits
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(Key, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream
                          (ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(Msg, 0, Msg.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }

        [HttpPost]
        public ActionResult Decryption(string Text2, string Key2)
        {
            // Convert String to Byte
            byte[] MsgBytes = Convert.FromBase64String(Text2);
            byte[] KeyBytes = Encoding.UTF8.GetBytes(Key2);
            KeyBytes = SHA256.Create().ComputeHash(KeyBytes);

            byte[] bytesDecrypted = AES_Decryption(MsgBytes, KeyBytes);

            string decryptionText = Encoding.UTF8.GetString(bytesDecrypted);

            TempData["TDecrypted"] = decryptionText;
            return RedirectToAction("Index");
        }

        public byte[] AES_Decryption(byte[] Msg, byte[] Key)
        {
            byte[] decryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(Key, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream
                          (ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(Msg, 0, Msg.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }
    }
}

Right click on the Index (Action) -> Select "Add View".

Image 11

HTML
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Encryption And Decryption</h2>
 
<div style="color:red;" id="EncryptedText"
>Encrypted Message: @ViewData["Encrypted"]</div>
 
<div style="color:red;" id="DecryptedText"
>Decrypted Message: @ViewData["Decrypted"]</div>
 
<pre>
@using(Html.BeginForm("Encryption", "AES", FormMethod.Post))
{
     &lt;label id="lbk1">Key:&lt;/label>
     &lt;input name="Key" id="Key" type="text" />
    <br />
<br />
     &lt;label id="lbk2">Message:&lt;/label>
     &lt;input name="Text" id="Text" type="text" />
    <br />
<br />
    &lt;input id="btnEncryption" type="submit" value="Encryption" />
    <br />  
    <br />          
}

How to Test Application

For encryption:

  1. Enter Key such as: Key=122
  2. Enter Message: Message=Mahsa
  3. Press "Encryption" button
  4. You will see cypher text --> Encrypted Message: 7gkI7SpPzsOiJ8O2OO2jOQ==

For decryption:

  1. Enter Same Key="122"
  2. Enter Encrypted Message --> 7gkI7SpPzsOiJ8O2OO2jOQ==
  3. Press "Decryption" button
  4. You will See: Decrypted Message: Mahsa

Security Assertion Markup Language (SAML)

SAML is XML-based and open standard that formats data which is supposed to transfer user information as an encrypted data between an identity provider and service provider. It includes a specific tag which contains this encrypted data.

<saml:Assertion ..> 
"includes important message from identity provider to service provider
"Who is this user (Attribute Identity)
 "Is he/she allowed to consume service?
</saml:Assertion>

SAML protocol is requested when service provider calls direct query to identity provider over secure channel. Popular using from SAML is for Web Browser Single Sign-On (SSO). In this issue, the below matters happens by using SAML:

  1. Request Target Resource

    User enters www.sample.com inside address bar via web browser such as Chrome or Mozila, for example: http://www.stackoverflow.com/ and sends a request to use specific service from stackoverflow as service provider. This user can enter its username and password directly from using stack authentication or choose one of the authentication options from log in page.

  2. Redirect to the SSO Service

    Assume that user selects Google option for authentication process, then stackoverflow will redirect him/her from http://www.stackoverflow.com/ to https://accounts.google.com.

  3. Request SSO Service

    In this example, stackoverflow is a service provider which provides desired service for user and Google.com is an identity provider which does Single Sign-On for user. Google identifies user by requesting some information which belongs to user such as username and password and checks if these credentials are valid or not. Identity providers use directory services such as LDAP, Radius and Active Directory to authentication process.

  4. Respond with XHTML Form

    In this stage, user should press on Accept button inside Google.com as identity provider to allow some of his/her information such as username and email pass and transmit to service provider. When he/she does it, identity provider responds with XHTML form (below code) to service provider.

    HTML
    <form method="post" action="https://sp.example.com/SAML2/SSO/POST" ...>
        <input type="hidden" name="SAMLResponse" value="response" />
        <input type="submit" value="Submit" />
    </form>
  5. Request Assertion Consumer Service

    If in the above XHTML, identity provider allows user to consume services from service provider so user redirects to service provider while he/she is a valid user for that site and can consume desired services. (Although in this stage, service provider makes the authorisation process to check his/her access permission to consume each service).

  6. Redirect to Target Resource

    In this stage, service provider makes authorisation process to check his/her access permission to consume each service and then user will be redirected to target resource.

  7. Request Target Resource

    User requests specific resource from service provider and as I mentioned above if the permission is confirmed from service provider, so user can consume it. Such as http://astronomy.stackexchange.com/

  8. Respond with Requested Resource

    If user has permission to access that service, so service provider will redirect user to resource.

Image 12

Dictionary

In this section, I have explained some of the specific words which need more description. This part can solve misunderstanding and appear my intentions to use these words in my writing style.

XML

Extensible Markup Language is a markup language that includes specific rules to encode and format documents so that they are readable for humans and machine. XML is useful for working on the web application and services to organize different kind of data structures and human languages.

XML has rules to define how to arrange our content. It includes tag which is “<div></div>”, attribute such as class attribute inside “<div class=”class1”></div>”, finally our data is located inside tags for instance “Hello” inside “<div class=”class1”>Hello</div>” and its declaration starts with <?xml version="1.0" encoding="UTF-8"?>.

Security Token

Security token is a device that produces key for authentication process. It is an additional tool to make high security to detect if user is really who claims or not. It is a device such as Key Generator, USB Connector, and Bluetooth Wireless. It sores a key for cryptography issues (encryption and decryption functions) and this key can be a biometric signs such as fingerprint or digital signature. This key with specific cryptography function can generate a new digital number and users enter this digital number after their username and password. This key proves user's claim is he/she really who claims or not. In the figure, user should enter username and password and then press the key on device and enter number “54392971” to passcode, then click on “Log On”.

Image 13

Service Provider

Service Provider is called to company where provides list of services to its customers. These services are categorized to telecommunication, application, storage place, and internet.

Identity Provider

Identity Provider is a third party, outside from two parts (authentication situation has two parts consumer as user and supplier as service provider) to detect if user is an authorized user and give some important information of user to service provider, finally authorized user has permission to consume services.

For an instance, stackoverflow.com is a supplier (service provider), where you can ask your question in related section. If user wants to log in this site, it has some options to do that such as Log in using Google, Facebook, Yahoo, LiveJournal, WordPress, Blogger, Verisign and AOL or by stackoverflow. If user selects stackoverflow, then he/she should create username and password for this site and enter all of the repetitive information here again. Whenever user selects other options which are Identity Providers, then he will be redirected from stackoverflow to these websites and enter specific username and password to them, then these sites decide if this user is valid or not? If user is valid, so user's information such as email address will be passed to stackoverflow site. Important security issue in his story is that Identity Provider (IP) will not be found out this person is going to do what action and user privacy will be protected.

Image 14

Image 15

Redirect to Google for authentication issue (using Google account to log in Stackoverflow.com).

LDAP

Lightweight Directory Access Protocol (LDAP) is an internet protocol. LDAP looks up information by making index for each data and filtering just specific item which is wanted.

Active Directory

Active Directory is a directory service based on windows domain with services to authenticate and authorize. Users log on to computer which is in the windows domain and active directory checks submitted password by LDAP, if username and password has right to access then active directory, permit it to use desired services.

Windows Domain

Windows domain is a kind of network so that all users and computers and their peripherals are registered on the central computer.

Federated Identity Provider

Federated identity is a technology to make a link between user identity (username and password) and other identity management in order to authenticate user and inform source node that user is valid. It means you can have just one username and password and be valid across multiple web sites. Single Sign-On is subset of federated identity.

U-Prove

U-Prove is a cryptographic technology that reveals minimum information about user who wants to go through multiple web sites, especially when user interacts with identity provider. U-Prove makes it hard to track what user wants to do. U-Prove token encrypts information with two features. Firstly, the cryptographic “wrapping” of information without correlation handles causes to avoid tracking of user. Secondly, users disclose minimum of their information in verifier policy process such as “age” without explicit revealing “birth date”.

OpenID

OpenID is a protocol that allows users to continue their authentication process by other web sites are called “Relying Parties” as a third party such as Google, Microsoft, Facebook, AOL, etc.

Stateless and Stateful

Stateless is a communication protocol that establishes independent request and response among client and server. It does not need the server to keep its information about communication between requester and responder in contrast Stateful needs server to keep information about its status. Internet Protocol, IP foundation for the internet and Hyper Text Transfer Protocol, HTTP, foundation of data communication on the web are examples for stateless. Transmission Control Protocol TCP is example for Stateful that provides a reliable and error checked communication between client and server.

Conclusion

I used one of the most popular cryptography techniques as AES in my application. AES is a symmetric encryption function by using the same secret key in the sender and receiver sides and AES produces strong key which hackers are not able to break it. So AES is a good way to keep data confidential and integrity.

History

  • 31st August, 2015: First version

Feedback

Feel free to leave any feedback on this article; it is a pleasure to see your opinions and vote about this code. If you have any questions, please do not hesitate to ask me here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)