Sie sind auf Seite 1von 23

C# – Encrypt/Decrypt Password

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace SecurePassword
{
class Encode_Decode
{
public static class Global
{
// set password
public const string strPassword = "LetMeIn99$";

// set permutations
public const String strPermutation = "ouiveyxaqtd";
public const Int32 bytePermutation1 = 0x19;
public const Int32 bytePermutation2 = 0x59;
public const Int32 bytePermutation3 = 0x17;
public const Int32 bytePermutation4 = 0x41;
}

// The console window


public static void Main(String[] args)
{

Console.Title = "Secure Password v2";


Console.WriteLine("Output---");
Console.WriteLine("");

Console.WriteLine("Password: " + Global.strPassword);

string strEncrypted = (Encrypt(Global.strPassword));


Console.WriteLine("Encrypted: " + strEncrypted);

string strDecrypted = (Decrypt(strEncrypted));


Console.WriteLine("Decrypted: " + strDecrypted);

Console.ReadKey();
}

// encoding
public static string Encrypt(string strData)
{

return
Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(strData)));
// reference https://msdn.microsoft.com/en-
us/library/ds4kkd55(v=vs.110).aspx
}

// decoding
public static string Decrypt(string strData)
{
return
Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(strData)));
// reference https://msdn.microsoft.com/en-
us/library/system.convert.frombase64string(v=vs.110).aspx

// encrypt
public static byte[] Encrypt(byte[] strData)
{
PasswordDeriveBytes passbytes =
new PasswordDeriveBytes(Global.strPermutation,
new byte[] { Global.bytePermutation1,
Global.bytePermutation2,
Global.bytePermutation3,
Global.bytePermutation4
});

MemoryStream memstream = new MemoryStream();


Aes aes = new AesManaged();
aes.Key = passbytes.GetBytes(aes.KeySize/8);
aes.IV = passbytes.GetBytes(aes.BlockSize/8);

CryptoStream cryptostream = new CryptoStream(memstream,


aes.CreateEncryptor(), CryptoStreamMode.Write);
cryptostream.Write(strData, 0, strData.Length);
cryptostream.Close();
return memstream.ToArray();
}

// decrypt
public static byte[] Decrypt(byte[] strData)
{
PasswordDeriveBytes passbytes =
new PasswordDeriveBytes(Global.strPermutation,
new byte[] { Global.bytePermutation1,
Global.bytePermutation2,
Global.bytePermutation3,
Global.bytePermutation4
});

MemoryStream memstream = new MemoryStream();


Aes aes = new AesManaged();
aes.Key = passbytes.GetBytes(aes.KeySize/8);
aes.IV = passbytes.GetBytes(aes.BlockSize/8);

CryptoStream cryptostream = new CryptoStream(memstream,


aes.CreateDecryptor(), CryptoStreamMode.Write);
cryptostream.Write(strData, 0, strData.Length);
cryptostream.Close();
return memstream.ToArray();
}
// reference
// https://msdn.microsoft.com/en-
us/library/system.security.cryptography(v=vs.110).aspx
// https://msdn.microsoft.com/en-
us/library/system.security.cryptography.cryptostream%28v=vs.110%29.aspx?f=2
55&MSPPError=-2147217396
// https://msdn.microsoft.com/en-
us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx
// https://msdn.microsoft.com/en-
us/library/system.security.cryptography.aesmanaged%28v=vs.110%29.aspx?f=255
&MSPPError=-2147217396
}
}

How to Encrypt or Decrypt password using


Asp.Net with c#
Enter Your Password and first click on Encrypt button and then after click on Decrypt.

1. Example Of First Enter Password = "rraannaammeett"


2. EncodePasswordToBase64 function convert your string and give output
ans= "cnJhYW5uYWFtbWVldHQ= "
3. DecodeFrom64 function convert your strring and give output
ans="rraannaammeett"

//this function Convert to Encord your Password


public static string EncodePasswordToBase64(string password)
{
try
{
byte[] encData_byte = new byte[password.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
} //this function Convert to Decord your Password
public string DecodeFrom64(string encodedData)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encodedData);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text=EncodePasswordToBase64(TextBox1.Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = DecodeFrom64(Label1.Text);}

C# Encryption and Decryption of a String With a Simple Function

Encryption and decryption of a password or other strings containing data can be done in many
ways. There are many character substitution or transposition methods that pre-date the
computing era and can be traced back to classical times. Modern computer based methods use
symmetric key and asymmetric key mathematical algorithms. There are lots of well
established algorithms from which to choose. However not everyone wants to take a course in
cryptography just to be able to encrypt a string to hide some data and decrypt it back again.
That’s where this example C# encryption and decryption code comes in handy. This code was
tested in Visual Studio 2013. (Update: Tested OK in Visual Studio 2017)

String Encryption and Decryption for Basic Low Level Confidentiality

The following C# code has been boiled down to an encryption function that takes a plaintext
string and passphrase and returns an encrypted string. There is the reverse function that takes
the ciphertext and the passphrase and returns the plaintext. This is a quick and easy method of
adding some encryption to a C# project, or any .NET project. The encrypt decrypt C# string
functions are in a simple class. An example project shows how simple it is to use them. Thus:

Encryption of a string in C# with a password is as simple as:

textBoxEncrypted.Text = Encrypt.EncryptString(textBoxString.Text,
textBoxPassword.Text);

Decryption is just as easy:

textBoxString.Text = Encrypt.DecryptString(textBoxEncrypted.Text,
textBoxPassword.Text);

Overview of the Encryption and Decryption Functions

The code presented here is not going to be explained in detail. Instead it is recommended that
it is studied. The reader should to refer to online resources and the Microsoft .NET
Framework documentation on the System.Security.Cryptography namespace. The code was
picked up from the Stack Overflow question Encrypting and Decrypting a String in C#. The
encrypt and decrypt demo source code in this article should be easy enough to use in your
project.

This code is using a symmetric key algorithm known as Rijndael (after the inventors Vincent
Rijmen and Joan Daemen), which is implemented by the .NET Framework. This algorithm
performs substitutions and permutations on data blocks with keys sized in multiples of 32
bits. The cipher mode is Cipher Block Chaining (CBC) which can take a different
Initialisation Vector (IV) for each use to further obfuscate the cipher text. In which case the
same passphrase and plaintext will produce different ciphertexts if a different IV is used.
Important: Change the IV string for you own value or generate a random one (this can be
done at https://www.random.org/strings/). The passphrase is not salted but can be, see the
documentation for PasswordDeriveBytes. Note that the encryption and decryption is
performed on bytes and not Unicode characters hence the conversion from strings to byte
arrays in the code (it also means that these functions can be adapted for other data types if
required).

The Free to Use Encryption and Decryption C# Code


//Don't forget the using System.Security.Cryptography; statement when you
add this class
public static class Encrypt
{
// This size of the IV (in bytes) must = (keysize / 8). Default
keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes
when converted to a byte array.
private const string initVector = "pemgail9uzpgzl88";
// This constant is used to determine the keysize of the encryption
algorithm
private const int keysize = 256;
//Encrypt
public static string EncryptString(string plainText, string passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,
null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
//Decrypt
public static string DecryptString(string cipherText, string
passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,
null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0,
plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0,
decryptedByteCount);
}
}

The small example project (see the image at the top of the article) shows the encrypt decrypt
functionality in action. Create a similar WinForm or download the code, which has the dialog.

What is this?

This post contains examples of how to generate a SHA-256 and SHA-512 hash key with the
examples in C# and VB.NET

This solution matches the expected result for Ingenico's implementation for their payment
gateway.

C# - UPDATED

using System;
using System.Text;
using System.Security.Cryptography;
using CodeShare.Cryptography;

namespace CodeShare.Cryptography
{
public static class SHA
{

public static string GenerateSHA256String(string inputString)


{
SHA256 sha256 = SHA256Managed.Create();
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
byte[] hash = sha256.ComputeHash(bytes);
return GetStringFromHash(hash);
}

public static string GenerateSHA512String(string inputString)


{
SHA512 sha512 = SHA512Managed.Create();
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
byte[] hash = sha512.ComputeHash(bytes);
return GetStringFromHash(hash);
}

private static string GetStringFromHash(byte[] hash)


{
StringBuilder result = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
result.Append(hash[i].ToString("X2"));
}
return result.ToString();
}

}
}

Usage Example

public void UsageExample()


{
Console.WriteLine(SHA.GenerateSHA256String("abc"));
//returns
BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

Console.WriteLine(SHA.GenerateSHA512String("abc"));
//returns
DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274
FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F
}

Password Encryption using MD5 Hash


Algorithm in C#
Simple way to hash sensitive string.
using System.Text;
using System.Security.Cryptography;

namespace CryptoLib
{
public static class Encryptor
{
public static string MD5Hash(string text)
{
MD5 md5 = new MD5CryptoServiceProvider();

//compute hash from the bytes of text


md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));

//get hash result after compute it


byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}

return strBuilder.ToString();
}
}
}

Encrypt & Decrypt a String in C#

Encrypt and decrypt data using a symmetric key in C#.

Usage

var str = "String to be encrypted";


var password = "p@SSword";
var strEncryptred = Cipher.Encrypt(str, password);
var strDecrypted = Cipher.Decrypt(strEncryptred, password);

Cipher class

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace SG.Algoritma
{
public static class Cipher
{
/// <summary>
/// Encrypt a string.
/// </summary>
/// <param name="plainText">String to be encrypted</param>
/// <param name="password">Password</param>
public static string Encrypt(string plainText, string password)
{
if (plainText == null)
{
return null;
}

if (password == null)
{
password = String.Empty;
}

// Get the bytes of the string


var bytesToBeEncrypted = Encoding.UTF8.GetBytes(plainText);
var passwordBytes = Encoding.UTF8.GetBytes(password);

// Hash the password with SHA256


passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

var bytesEncrypted = Cipher.Encrypt(bytesToBeEncrypted,


passwordBytes);

return Convert.ToBase64String(bytesEncrypted);
}

/// <summary>
/// Decrypt a string.
/// </summary>
/// <param name="encryptedText">String to be decrypted</param>
/// <param name="password">Password used during encryption</param>
/// <exception cref="FormatException"></exception>
public static string Decrypt(string encryptedText, string password)
{
if (encryptedText == null)
{
return null;
}

if (password == null)
{
password = String.Empty;
}

// Get the bytes of the string


var bytesToBeDecrypted =
Convert.FromBase64String(encryptedText);
var passwordBytes = Encoding.UTF8.GetBytes(password);

passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

var bytesDecrypted = Cipher.Decrypt(bytesToBeDecrypted,


passwordBytes);

return Encoding.UTF8.GetString(bytesDecrypted);
}

private static byte[] Encrypt(byte[] bytesToBeEncrypted, byte[]


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

using (MemoryStream ms = new MemoryStream())


{
using (RijndaelManaged AES = new RijndaelManaged())
{
var key = new Rfc2898DeriveBytes(passwordBytes,
saltBytes, 1000);

AES.KeySize = 256;
AES.BlockSize = 128;
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(bytesToBeEncrypted, 0,
bytesToBeEncrypted.Length);
cs.Close();
}

encryptedBytes = ms.ToArray();
}
}

return encryptedBytes;
}

private static byte[] Decrypt(byte[] bytesToBeDecrypted, byte[]


passwordBytes)
{
byte[] decryptedBytes = null;

// Set your salt here, change it to meet your flavor:


// The salt bytes must be at least 8 bytes.
var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

using (MemoryStream ms = new MemoryStream())


{
using (RijndaelManaged AES = new RijndaelManaged())
{
var key = new Rfc2898DeriveBytes(passwordBytes,
saltBytes, 1000);

AES.KeySize = 256;
AES.BlockSize = 128;
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(bytesToBeDecrypted, 0,
bytesToBeDecrypted.Length);
cs.Close();
}

decryptedBytes = ms.ToArray();
}
}

return decryptedBytes;
}
}
}

Hash Passwords in C# and Visual Basic


Using SHA-512
We recently covered an easy way to hash passwords using SHA-1 in .NET using either Visual
Basic or C#. In most cases, SHA-1 encryption is “secure enough”, but there are some
mathematical weaknesses. Microsoft’s .NET platform (specifically the System.Security class)
allows you to encrypt passwords with a number of differnet algorithms without having to
know the mathematics behind them.

Today, we’re going to encrypt a string with SHA-2, specifically the SHA-512 derivation of
SHA-2, which should hypothetically be more secure than SHA-1 because it has a longer
message digest than SHA-1. The example code I’m going to show off today also uses a “salt“,
whereas the previous function I showed off didn’t. This will make your hashed-passwords
more immume to dictionary attacts because not only would the hacker have to develop a hash
for every commonly known password, but as well as every commonly known password
multiplied by the nearly infinite number of possible salts.

Here’s the function:

public static string CreateSHAHash(string Password, string Salt)


{
System.Security.Cryptography.SHA512Managed HashTool = new
System.Security.Cryptography.SHA512Managed();
Byte[] PasswordAsByte =
System.Text.Encoding.UTF8.GetBytes(string.Concat(Password, Salt));
Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}

How it works:

This method makes use of the System.Security.Cryptography class. It combines your


password and the salt that you provide and turns it into a byte-array. It runs those bytes
through the has computation function provided by the class and returns an 88-bit string of the
message-digest/hash that’s created.
Simple Encrypt and Decrypt Technique and
Computing Hash using C# in .NET
This article demonstrates how simply you can encrypt and decrypt simple text and compute hash
values

Introduction

This article will show you a simple approach of Encrypt and Decrypt techniques and
computing Hash values.

Background

Once I had to do cryptography in one of my projects. I did not have much knowledge about
this. I searched on the internet to get a better idea for a simple approach of doing Encryption
and Decryption and computing Hash values. But I did not find all of them in a single place.
This article will cover all these issues.

Using the Code

Open Visual Studio and open a new class library project. Add a class named
“CryptographyManager.cs”.

Hide Copy Code

public class CryptographyManager


{

Then add the following private member variables:

Hide Copy Code

private byte[] _keyByte = { };


//Default Key
private static string _key = Pass@123#;
//Default initial vector
private byte[] _ivByte = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78
};

We will have 3 Encrypt and 3 Decrypt methods using the method overloading technique.

Hide Shrink Copy Code

/// <summary>
/// Encrypt text
/// </summary>
/// <param name="value">plain text</param>
/// <returns>encrypted text</returns>
public string Encrypt(string value)
{
return Encrypt(value, string.Empty);
}

/// <summary>
/// Encrypt text by key
/// </summary>
/// <param name="value">plain text</param>
/// <param name="key"> string key</param>
/// <returns>encrypted text</returns>
public string Encrypt(string value, string key)
{
return Encrypt(value, key, string.Empty);
}

/// <summary>
/// Encrypt text by key with initialization vector
/// </summary>
/// <param name="value">plain text</param>
/// <param name="key"> string key</param>
/// <param name="iv">initialization vector</param>
/// <returns>encrypted text</returns>
public string Encrypt(string value, string key, string iv)
{
string encryptValue = string.Empty;
MemoryStream ms = null;
CryptoStream cs = null;
if (!string.IsNullOrEmpty(value))
{
try
{
if(!string.IsNullOrEmpty(key))
{
_keyByte = Encoding.UTF8.GetBytes
(key.Substring(0,8));
if (!string.IsNullOrEmpty(iv))
{
_ivByte = Encoding.UTF8.GetBytes
(iv.Substring(0, 8));
}
}
else
{
_keyByte = Encoding.UTF8.GetBytes(_key);
}
using (DESCryptoServiceProvider des =
new DESCryptoServiceProvider())
{
byte[] inputByteArray =
Encoding.UTF8.GetBytes(value);
ms = new MemoryStream();
cs = new CryptoStream(ms, des.CreateEncryptor
(_keyByte, _ivByte), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0,
inputByteArray.Length);
cs.FlushFinalBlock();
encryptValue =
Convert.ToBase64String(ms.ToArray());
}
}
catch
{
//TODO: write log
}
finally
{
cs.Dispose();
ms.Dispose();
}
}
return encryptValue;
}

/// <summary>
/// Decrypt text
/// </summary>
/// <param name="value">encrypted text</param>
/// <returns>plain text</returns>
public string Decrypt(string value)
{
return Decrypt(value, string.Empty);
}

/// <summary>
/// Decrypt text by key
/// </summary>
/// <param name="value">encrypted text</param>
/// <param name="key">string key</param>
/// <returns>plain text</returns>
public string Decrypt(string value, string key)
{
return Decrypt(value, key, string.Empty);
}

/// <summary>
/// Decrypt text by key with initialization vector
/// </summary>
/// <param name="value">encrypted text</param>
/// <param name="key"> string key</param>
/// <param name="iv">initialization vector</param>
/// <returns>encrypted text</returns>
public string Decrypt(string value, string key, string iv)
{
string decrptValue = string.Empty;
if (!string.IsNullOrEmpty(value))
{
MemoryStream ms = null;
CryptoStream cs = null;
value = value.Replace(" ", "+");
byte[] inputByteArray = new byte[value.Length];
try
{
if (!string.IsNullOrEmpty(key))
{
_keyByte = Encoding.UTF8.GetBytes
(key.Substring(0, 8));
if (!string.IsNullOrEmpty(iv))
{
_ivByte = Encoding.UTF8.GetBytes
(iv.Substring(0, 8));
}
}
else
{
_keyByte = Encoding.UTF8.GetBytes(_key);
}
using (DESCryptoServiceProvider des =
new DESCryptoServiceProvider())
{
inputByteArray =
Convert.FromBase64String(value);
ms = new MemoryStream();
cs = new CryptoStream(ms, des.CreateDecryptor
(_keyByte, _ivByte), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0,
inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
decrptValue =
encoding.GetString(ms.ToArray());
}
}
catch
{
//TODO: write log
}
finally
{
cs.Dispose();
ms.Dispose();
}
}
return decrptValue;
}

Now write methods to compute Hash values for a string.

There are different Hash techniques. So we are making an enumeration for those names.
Declare an Enum in the class:

Hide Copy Code

/// <summary>
/// Hash enum value
/// </summary>
public enum HashName
{
SHA1 = 1,
MD5 = 2,
SHA256 = 4,
SHA384 = 8,
SHA512 = 16
}

Now we will write two overloading methods for computing Hash values.

Hide Shrink Copy Code

/// <summary>
/// Compute Hash
/// </summary>
/// <param name="plainText">plain text</param>
/// <param name="salt">salt string</param>
/// <returns>string</returns>
public string ComputeHash(string plainText, string salt)
{
return ComputeHash(plainText, salt,HashName.MD5);
}

/// <summary>
/// Compute Hash
/// </summary>
/// <param name="plainText">plain text</param>
/// <param name="salt">salt string</param>
/// <param name="hashName">Hash Name</param>
/// <returns>string</returns>
public string ComputeHash(string plainText, string salt, HashName hashName)
{
if (!string.IsNullOrEmpty(plainText))
{
// Convert plain text into a byte array.
byte[] plainTextBytes =
ASCIIEncoding.ASCII.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes = null;
byte[] saltBytes;
if (!string.IsNullOrEmpty(salt))
{
// Convert salt text into a byte array.
saltBytes = ASCIIEncoding.ASCII.GetBytes(salt);
plainTextWithSaltBytes =
new byte[plainTextBytes.Length +
saltBytes.Length];
}
else
{
// Define min and max salt sizes.
int minSaltSize = 4;
int maxSaltSize = 8;
// Generate a random number for the size of the
salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize,
maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rngCryptoServiceProvider =
new
RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte
values.
rngCryptoServiceProvider.GetNonZeroBytes(saltBytes);
}
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
{
plainTextWithSaltBytes[i] = plainTextBytes[i];
}
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
{
plainTextWithSaltBytes[plainTextBytes.Length + i] =
saltBytes[i];
}
HashAlgorithm hash = null;
switch (hashName)
{
case HashName.SHA1:
hash = new SHA1Managed();
break;
case HashName.SHA256:
hash = new SHA256Managed();
break;
case HashName.SHA384:
hash = new SHA384Managed();
break;
case HashName.SHA512:
hash = new SHA512Managed();
break;
case HashName.MD5:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt
bytes.
byte[] hashWithSaltBytes =
new byte[hashBytes.Length + saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
{
hashWithSaltBytes[i] = hashBytes[i];
}
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
{
hashWithSaltBytes[hashBytes.Length + i] =
saltBytes[i];
}
// Convert result into a base64-encoded string.
string hashValue =
Convert.ToBase64String(hashWithSaltBytes);
// Return the result.
return hashValue;
}
return string.Empty;
}

Points of Interest

This code can be used in any .NET project for quick encryption and decryption of any text
using DESCryptography algorithm.

Encrypt And Decrypt User Password In


SQL Server DB Using C# Winform
Application
In this article, we are going to learn how to maintain the user login details in SQL server table
with password encryption format and decrypt the user password and validate the credentials in
the login form.

Step 1

Create the Database and table to maintain the user login credentials.

Here, I have created my database and named it as "LoginDB" and created a table
"tblUserRegistration" to maintain the user credentials.

Please refer to the below image for your reference.

Note

The table "tblUserRegistration" has three columns - Id, UserName, Password. Id is a primary
key; set its identification to yes and initialize starting value as1. UserName and Password are
string values, so I set these as varchar datatype.

Step 2

Let's create a simple Windows application in Visual Studio.

To create a Windows application, open Visual Studio and go to New Project. A new dialog
window will appear.; Click C# in the left pane and select Windows Form Application there.
Name your project and click OK.

Here, I have created my project and named it as "EncryptionandDecryption". Now, we will


design our user registration form for registering new user credentials.

Step 3

Now, let's create a simple class file in our project to write encryption and decryption logic.To
add a class file, right click your project -> Add -> New item -> select class in the dialog box
and name your class file. Click OK.

Here, I have created my class file and named it as "Cryptography". Now, we can write our
encryption and decryption logic.

Please find the below code for your reference.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Security.Cryptography;
6. using System.IO;
7.
8. namespace EncryptionandDecryption
9. {
10. public class Cryptography
11. {
12. public static string Encrypt(string encryptString)
13. {
14. string EncryptionKey = "0ram@1234xxxxxxxxxxtttttuuuuuiiiiio"; //we can ch
ange the code converstion key as per our requirement
15. byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);
16. using (Aes encryptor = Aes.Create())
17. {
18. Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new
byte[] {
19. 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x7
6
20. });
21. encryptor.Key = pdb.GetBytes(32);
22. encryptor.IV = pdb.GetBytes(16);
23. using (MemoryStream ms = new MemoryStream())
24. {
25. using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryp
tor(), CryptoStreamMode.Write))
26. {
27. cs.Write(clearBytes, 0, clearBytes.Length);
28. cs.Close();
29. }
30. encryptString = Convert.ToBase64String(ms.ToArray());
31. }
32. }
33. return encryptString;
34. }
35.
36. public static string Decrypt(string cipherText)
37. {
38. string EncryptionKey = "0ram@1234xxxxxxxxxxtttttuuuuuiiiiio"; //we can ch
ange the code converstion key as per our requirement, but the decryption key should b
e same as encryption key
39. cipherText = cipherText.Replace(" ", "+");
40. byte[] cipherBytes = Convert.FromBase64String(cipherText);
41. using (Aes encryptor = Aes.Create())
42. {
43. Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new
byte[] {
44. 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x7
6
45. });
46. encryptor.Key = pdb.GetBytes(32);
47. encryptor.IV = pdb.GetBytes(16);
48. using (MemoryStream ms = new MemoryStream())
49. {
50. using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryp
tor(), CryptoStreamMode.Write))
51. {
52. cs.Write(cipherBytes, 0, cipherBytes.Length);
53. cs.Close();
54. }
55. cipherText = Encoding.Unicode.GetString(ms.ToArray());
56. }
57. }
58. return cipherText;
59. }
60. }
61. }

Step 4

Let's write a code for registering a new user on Register button click event. Please find the
below code for your reference.

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace EncryptionandDecryption
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=172.18.1.3;Initial
Catalog=LoginDB;User ID=prog;Password=XqvF^D2$wJ");

private void btnRegister_Click(object sender, EventArgs e)


{
if (txtUserName.Text != "" && txtPassword.Text != "" &&
txtConfirmPassword.Text != "") //validating the fields whether the fields or empty or not
{
if (txtPassword.Text.ToString().Trim().ToLower() ==
txtConfirmPassword.Text.ToString().Trim().ToLower()) //validating Password textbox and
confirm password textbox is match or unmatch
{
string UserName = txtUserName.Text;
string Password = Cryptography.Encrypt(txtPassword.Text.ToString()); //
Passing the Password to Encrypt method and the method will return encrypted string and
stored in Password variable.
con.Open();
SqlCommand insert=new SqlCommand("insert into
tblUserRegistration(UserName,Password)values('"+UserName+"','"+Password+"')",con);
insert.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Password and Confirm Password doesn't match!..
Please Check..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information); //showing
the error message if password and confirm password doesn't match
}
}
else
{
MessageBox.Show("Please fill all the fields!..", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Information); //showing the error message if any
fields is empty
}
}
}
}

Let's create a new registration and check the DB how the password has stored. Please find the
below images for your reference.

Step 5

Now, we will design our login form and compare with DB. But here, we have encrypted our
password in DB.The user is not aware of that. So in the back-end, we have to decrypt the user
password and need to check.

Let's see how to do that.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace EncryptionandDecryption
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=RAMESH-PC;Initial
Catalog=LoginDB;Integrated Security=True");
private void btnLogin_Click(object sender, EventArgs e)
{
string Password = "" ;
bool IsExist = false;
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblUserRegistration where
UserName='" + txtUserName.Text + "'", con);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
Password = sdr.GetString(2); //get the user password from db if the user name is
exist in that.
IsExist = true;
}
con.Close();
if (IsExist) //if record exis in db , it will return true, otherwise it will return false
{
if (Cryptography.Decrypt(Password).Equals(txtPassword.Text))
{
MessageBox.Show("Login Success", "Success", MessageBoxButtons.OK,
MessageBoxIcon.Information);
Form1 frm1 = new Form1();
frm1.ShowDialog();
}
else
{
MessageBox.Show("Password is wrong!...", "error",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

}
else //showing the error message if user credential is wrong
{
MessageBox.Show("Please enter the valid credentials", "error",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

}
}
}

Thanks for reading my article. Please post comments if you have any feedback or queries.

Das könnte Ihnen auch gefallen