using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Diagnostics.Metrics;
namespace EasyDevCore.Common.Security
{
///
///
///
public enum SymmetricAlgorithmMethod
{
///
/// The DES crypto service provider
///
DESCryptoServiceProvider,
///
/// The rijndael managed
///
RijndaelManaged,
///
/// The R c2 crypto service provider
///
RC2CryptoServiceProvider,
///
/// The triple DES crypto service provider
///
TripleDESCryptoServiceProvider
}
///
///
///
public enum AsymmetricAlgorithmMethod
{
///
/// The DSA
///
DSA,
///
/// The EC diffie hellman
///
ECDiffieHellman,
///
/// The EC DSA
///
ECDsa,
///
/// The RSA
///
RSA
}
/// Security Helper
public sealed class EncryptionHelper
{
#region Private Variables
//Original key to ensure it complex
private static string _KeyStringDump = "1AXDHKDASF932CXK";
#endregion
#region Public Methods
///
/// Sets the dump key string - original key to ensure it enough complex.
///
/// The dump key.
public static void SetDumpKeyString(string dumpKey)
{
_KeyStringDump = dumpKey;
}
private static SymmetricAlgorithm GetCryptorServiceProvider(SymmetricAlgorithmMethod algorithm)
{
if(OperatingSystem.IsBrowser())
{
throw new NotSupportedException();
}
switch (algorithm)
{
case SymmetricAlgorithmMethod.DESCryptoServiceProvider:
return DES.Create();
case SymmetricAlgorithmMethod.RC2CryptoServiceProvider:
return RC2.Create();
case SymmetricAlgorithmMethod.RijndaelManaged:
return Aes.Create();
case SymmetricAlgorithmMethod.TripleDESCryptoServiceProvider:
return TripleDES.Create();
default:
throw new NotSupportedException(algorithm.ToString());
}
}
///
/// RSAs the generate keys.
///
/// The XML public key.
/// The XML private key.
/// Size of the key.
public static void RSAGenerateKeys(ref string xmlPublicKey, ref string xmlPrivateKey, int keySize)
{
if (OperatingSystem.IsBrowser())
{
throw new NotSupportedException();
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize))
{
xmlPublicKey = rsa.ToXmlString(false);
xmlPrivateKey = rsa.ToXmlString(true);
}
}
///
/// RSAs the encrypt data.
///
/// The XML public key.
/// The data.
///
public static byte[] RSAEncryptData(string xmlPublicKey, byte[] data)
{
if (OperatingSystem.IsBrowser())
{
throw new NotSupportedException();
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(xmlPublicKey);
return rsa.Encrypt(data, false);
}
}
///
/// RSAs the encrypt string.
///
/// The XML public key.
/// The data string.
///
public static string RSAEncryptString(string xmlPublicKey, string dataString)
{
string valueEncodeString = string.Empty;
//convert data to byte array
byte[] byteData = Encoding.UTF8.GetBytes(dataString);
byte[] encryptedData = RSAEncryptData(xmlPublicKey, byteData);
//convert to string and Base64 encode
valueEncodeString = Convert.ToBase64String(encryptedData);
return valueEncodeString;
}
///
/// RSAs the decrypt data.
///
/// The XML private key.
/// The data.
///
public static byte[] RSADecryptData(string xmlPrivateKey, byte[] data)
{
if (OperatingSystem.IsBrowser())
{
throw new NotSupportedException();
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(xmlPrivateKey);
return rsa.Decrypt(data, false);
}
}
///
/// RSAs the decrypt string.
///
/// The XML P private key.
/// The encrypted data string.
///
public static string RSADecryptString(string xmlPPrivateKey, string encryptedDataString)
{
//convert data to byte array
byte[] encryptedData = Convert.FromBase64String(encryptedDataString);
byte[] byteData = RSADecryptData(xmlPPrivateKey, encryptedData);
// convert to string
System.Text.Encoding objEncoding = System.Text.Encoding.UTF8;
return objEncoding.GetString(byteData);
}
///
/// Encrypts the data.
///
/// The key string.
/// The algorithm.
/// The data.
///
public static byte[] EncryptData(string keyString, SymmetricAlgorithmMethod algorithm, byte[] data)
{
string valueEncodeString = string.Empty;
using (MemoryStream objMemoryStream = new MemoryStream())
{
if ((data.Length > 0) && keyString != string.Empty)
{
//convert key to atleast KeyString.Length characters for complex
if (keyString.Length < _KeyStringDump.Length)
{
keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
}
//create encryption keys
byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
//encrypt
using (var objCryptor = GetCryptorServiceProvider(algorithm))
{
CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write);
objCryptoStream.Write(data, 0, data.Length);
objCryptoStream.FlushFinalBlock();
}
}
else
{
objMemoryStream.Write(data, 0, data.Length);
}
return objMemoryStream.ToArray();
}
}
///
/// Decrypts the data.
///
/// The key string.
/// The data.
///
public static byte[] DecryptData(string keyString, byte[] data)
{
return DecryptData(keyString, SymmetricAlgorithmMethod.DESCryptoServiceProvider, data);
}
///
/// Decrypts the data.
///
/// The key string.
/// The algorithm.
/// The data.
///
public static byte[] DecryptData(string keyString, SymmetricAlgorithmMethod algorithm, byte[] data)
{
using (MemoryStream objMemoryStream = new MemoryStream())
{
if ((data.Length > 0) && keyString != string.Empty)
{
//convert key to atleast KeyString.Length characters for complex
if (keyString.Length < _KeyStringDump.Length)
{
keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
}
//create encryption keys
byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
// decrypt
using (var objCryptor = GetCryptorServiceProvider(algorithm))
{
CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
objCryptoStream.Write(data, 0, data.Length);
objCryptoStream.FlushFinalBlock();
}
}
else
{
objMemoryStream.Write(data, 0, data.Length);
}
return objMemoryStream.ToArray();
}
}
///
/// Encrypts the string.
///
/// The key string.
/// The data string.
///
public static string EncryptString(string keyString, string dataString)
{
string valueEncodeString = string.Empty;
if (keyString != string.Empty && dataString != null)
{
//convert key to atleast KeyString.Length characters for complex
if (keyString.Length < _KeyStringDump.Length)
{
keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
}
//create encryption keys
byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
//convert data to byte array
byte[] byteData = Encoding.UTF8.GetBytes(dataString);
//encrypt
using(var objCryptor = GetCryptorServiceProvider(SymmetricAlgorithmMethod.DESCryptoServiceProvider))
{
MemoryStream objMemoryStream = new MemoryStream();
CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write);
objCryptoStream.Write(byteData, 0, byteData.Length);
objCryptoStream.FlushFinalBlock();
//convert to string and Base64 encode
valueEncodeString = Convert.ToBase64String(objMemoryStream.ToArray());
}
}
else
{
valueEncodeString = dataString;
}
return valueEncodeString;
}
///
/// Decrypts the string.
///
/// The key string.
/// The data string.
///
public static string DecryptString(string keyString, string dataString)
{
if (string.IsNullOrWhiteSpace(dataString))
{
return dataString;
}
string valueEncodeString = string.Empty;
if (keyString != string.Empty)
{
//convert key to atleast KeyString.Length characters for complex
if (keyString.Length < _KeyStringDump.Length)
{
keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
}
//create encryption keys
byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
//convert data to byte array and Base64 decode
byte[] byteData = new byte[dataString.Length];
try
{
byteData = Convert.FromBase64String(dataString);
}
catch // invalid length
{
valueEncodeString = dataString;
}
if (valueEncodeString == string.Empty)
{
try
{
// decrypt
using(var objCryptor = GetCryptorServiceProvider(SymmetricAlgorithmMethod.DESCryptoServiceProvider))
{
MemoryStream objMemoryStream = new MemoryStream();
CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
objCryptoStream.Write(byteData, 0, byteData.Length);
objCryptoStream.FlushFinalBlock();
// convert to string
System.Text.Encoding objEncoding = System.Text.Encoding.UTF8;
valueEncodeString = objEncoding.GetString(objMemoryStream.ToArray());
}
}
catch // decryption error
{
return string.Empty;
}
}
return valueEncodeString;
}
else
{
return dataString;
}
}
///
/// Complex Encrypts the string.
///
/// The key string.
/// The data string.
///
public static string ComplexEncryptString(string keyString, string dataString)
{
if (string.IsNullOrEmpty(dataString))
{
return string.Empty;
}
if(dataString.IndexOf((char)0) > -1)
{
throw new NotSupportedException($"{nameof(dataString)} contains invalid characters !");
}
Random rand = new Random(DateTime.Now.Millisecond);
int dump = rand.Next(1, 30 - (dataString.Length % 20));
if (dump > 0)
{
string dumpString = string.Empty;
for (int i = 0; i < dump; i++)
{
dumpString += (char)(rand.Next(254) + 1);
}
if ((dumpString.Length + dataString.Length) % 2 == 0)
{
dataString += (char)0 + dumpString;
}
else
{
dataString = dumpString + (char)0 + dataString;
}
}
return EncryptString(keyString, dataString);
}
///
/// Complex Decrypts the string.
///
/// The key string.
/// The data string.
///
public static string ComplexDecryptString(string keyString, string dataString)
{
if (string.IsNullOrEmpty(dataString))
{
return string.Empty;
}
string decryptString = DecryptString(keyString, dataString);
if (dataString.Length > 0 && decryptString.Length == 0) decryptString = dataString;
int pos = decryptString.IndexOf((char)0);
if (pos > 0)
{
if ((decryptString.Length - 1) % 2 == 0)
{
decryptString = decryptString.Substring(0, pos);
}
else
{
decryptString = decryptString.Substring(pos + 1);
}
}
return decryptString;
}
#endregion
}
}