String Encryption and Decryption

A Beginner's Guide to Encryption c# asp.net

Password storage is a large topic in application security. A hashed representation of the password, using a contemporary encryption algorithm and process, is the accepted way to store a password in today's systems. Hashing is a one way function . It is irreversible, you apply the secure hash algorithm and you cannot get the original string back. Unlike a hash, you're not going to be storing this anywhere, as it is your secret key for your symmetric operation, so there's less risk of an attacker trying to find a recover the passphrase mostly because they just don't need to.

RFC2898DeriveBytes Class

Using RFC2898DeriveBytes with a non trivial iteration count should be better than using a straight hash function for authentication purposes. The Rfc2898DeriveBytes class can be used to produce a derived key from a base key and other parameters. In a password-based key derivation function, the base key is a password and the other parameters are a salt value and an iteration count.

PBKDF2

How to encrypt and decrypt password in asp.net c#

Rfc2898DeriveBytes is an implementation of PBKDF2. PBKDF2 uses a pseudorandom function and a configurable number of iterations to derive a cryptographic key from a password. Because this process is difficult to reverse but can also be configured to be slow to compute, key derivation functions are ideally suited for password hashing use cases. The details of PBKDF2 are openly published. The goal is one of "key stretching", making the overall process of generating or reversing the hash harder. The .NET Framework can abstract the details of the algorithm from the developer.

AES

AES Represents the abstract base class from which all implementations of the Advanced Encryption Standard (AES) must inherit. It has specific vulnerabilities with related key attacks. Related key attacks are possible when an attacker knows some data encrypted with several keys, and there is some known relation between them.

System.Security.Cryptography

The System.Security.Cryptography namespace provides cryptographic services, including secure encoding and decoding of data

Encrypt and Decrypt a String

From the following program you can learn how to Encrypt a string and Decrypt an Encrypted String

C# Source Code

using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //You should  not hard code the encryption key here
            string EncryptionKey = "encryptionkey";
            string eStr = passwordEncrypt("yourpassword", EncryptionKey);
            MessageBox.Show(eStr);
            string dStr = passwordDecrypt(eStr, EncryptionKey);
            MessageBox.Show(dStr);
        }
		//Encrypting a string
        public static string passwordEncrypt(string inText, string key)
        {
            byte[] bytesBuff = Encoding.Unicode.GetBytes(inText);
            using (Aes aes = Aes.Create())
            {
                Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                aes.Key = crypto.GetBytes(32);
                aes.IV = crypto.GetBytes(16);
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bytesBuff, 0, bytesBuff.Length);
                        cStream.Close();
                    }
                    inText = Convert.ToBase64String(mStream.ToArray());
                }
            }
            return inText;
        }
		//Decrypting a string
        public static string passwordDecrypt(string cryptTxt,string key)
        {
            cryptTxt = cryptTxt.Replace(" ", "+");
            byte[] bytesBuff = Convert.FromBase64String(cryptTxt);
            using (Aes aes = Aes.Create())
            {
                Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                aes.Key = crypto.GetBytes(32);
                aes.IV = crypto.GetBytes(16);
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bytesBuff, 0, bytesBuff.Length);
                        cStream.Close();
                    }
                    cryptTxt = Encoding.Unicode.GetString(mStream.ToArray());
                }
            }
            return cryptTxt;
        }
    }
}

Password Security and Encryption

VB.Net Source Code

Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'You should  not hard code the encryption key here
        Dim EncryptionKey As String = "encryptionkey"
        Dim eStr As String = passwordEncrypt("yourpassword", EncryptionKey)
        MessageBox.Show(eStr)
        Dim dStr As String = passwordDecrypt(eStr, EncryptionKey)
        MessageBox.Show(dStr)
    End Sub
	'Encrypting a string
    Public Shared Function passwordEncrypt(ByVal inText As String, ByVal key As String) As String
        Dim bytesBuff As Byte() = Encoding.Unicode.GetBytes(inText)
        Using aes__1 As Aes = Aes.Create()
            Dim crypto As New Rfc2898DeriveBytes(key, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
             &H65, &H64, &H76, &H65, &H64, &H65, _
             &H76})
            aes__1.Key = crypto.GetBytes(32)
            aes__1.IV = crypto.GetBytes(16)
            Using mStream As New MemoryStream()
                Using cStream As New CryptoStream(mStream, aes__1.CreateEncryptor(), CryptoStreamMode.Write)
                    cStream.Write(bytesBuff, 0, bytesBuff.Length)
                    cStream.Close()
                End Using
                inText = Convert.ToBase64String(mStream.ToArray())
            End Using
        End Using
        Return inText
    End Function
	'Decrypting a string
    Public Shared Function passwordDecrypt(ByVal cryptTxt As String, ByVal key As String) As String
        cryptTxt = cryptTxt.Replace(" ", "+")
        Dim bytesBuff As Byte() = Convert.FromBase64String(cryptTxt)
        Using aes__1 As Aes = Aes.Create()
            Dim crypto As New Rfc2898DeriveBytes(key, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
             &H65, &H64, &H76, &H65, &H64, &H65, _
             &H76})
            aes__1.Key = crypto.GetBytes(32)
            aes__1.IV = crypto.GetBytes(16)
            Using mStream As New MemoryStream()
                Using cStream As New CryptoStream(mStream, aes__1.CreateDecryptor(), CryptoStreamMode.Write)
                    cStream.Write(bytesBuff, 0, bytesBuff.Length)
                    cStream.Close()
                End Using
                cryptTxt = Encoding.Unicode.GetString(mStream.ToArray())
            End Using
        End Using
        Return cryptTxt
    End Function
End Class

Limitations

Safely Storing User Passwords asp.net c#

The built-in .NET implementation of Rfc2898DeriveBytes restrict the user to one pseudorandom function - HMAC with SHA-1. This is acceptable in most cases today, but in the future, a more complex hashing function may be required. Moreover, the .NET Compact Framework does not support Rfc2898DeriveBytes.



NEXT.....Datatype of a variable