Task: Encryption using SHA with encryptionkey in asp.net and c#..
Description: Encryption using SHA in asp.net and c#. Using below code we can generate message digest. In Web technology we need to save password of user, for this we can use this one. It is one way encryption, we can't decrypt it back.
Description: Encryption using SHA in asp.net and c#. Using below code we can generate message digest. In Web technology we need to save password of user, for this we can use this one. It is one way encryption, we can't decrypt it back.
using
System.Security.Cryptography;
public string shaEncrption(string
plainText, string encryptionkey)
{
try
{
string
key = encryptionkey;
byte[]
plainTextBytes = ASCIIEncoding.ASCII.GetBytes(plainText);
// Allocate
array, which will hold plain text and salt.
byte[]
plainTextWithkeyBytes = null;
byte[]
keyBytes;
if (!string.IsNullOrEmpty(key))
{
//
Convert salt text into a byte array.
keyBytes = ASCIIEncoding.ASCII.GetBytes(key);
plainTextWithkeyBytes =
new byte[plainTextBytes.Length
+ keyBytes.Length];
}
else
{
// Define
min and max salt sizes.
int
minkeySize = 4;
int
maxkeySize = 8;
//
Generate a random number for the size of the key.
Random
random = new Random();
int
keySize = random.Next(minkeySize, maxkeySize);
//
Allocate a byte array, which will hold the key.
keyBytes = new
byte[keySize];
//
Initialize a random number generator.
RNGCryptoServiceProvider
rngCryptoServiceProvider =
new RNGCryptoServiceProvider();
// Fill
the key with cryptographically strong byte values.
rngCryptoServiceProvider.GetNonZeroBytes(keyBytes);
}
// Copy plain
text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
{
plainTextWithkeyBytes[i] =
plainTextBytes[i];
}
// Append
salt bytes to the resulting array.
for (int i = 0; i < keyBytes.Length; i++)
{
plainTextWithkeyBytes[plainTextBytes.Length + i] =
keyBytes[i];
}
// SHA256
hash = new SHA256CryptoServiceProvider();
SHA384
hash = new SHA384CryptoServiceProvider();
// SHA512
hash = new SHA512CryptoServiceProvider();
byte[]
hashBytes = hash.ComputeHash(plainTextWithkeyBytes);
// Create
array which will hold hash and original key bytes.
byte[]
hashWithkeyBytes =
new
byte[hashBytes.Length + keyBytes.Length];
// Copy hash
bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
{
hashWithkeyBytes[i] = hashBytes[i];
}
// Append
salt bytes to the result.
for (int i = 0; i < keyBytes.Length; i++)
{
hashWithkeyBytes[hashBytes.Length +
i] = keyBytes[i];
}
// Convert
result into a base64-encoded string.
string
hashValue = Convert.ToBase64String(hashWithkeyBytes);
return
hashValue;
}
catch (Exception ex)
{
return null;
}
}