namespace Helper
{
using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
///
/// Clase núcleo para la encriptación.
///
public class CryptographyFoundation
{
///
/// Cantidad de interacciones para contraseñas.
///
private readonly int passwordIterations;
///
/// Inicializa una nueva instancia de la clase .
///
protected CryptographyFoundation()
{
this.passwordIterations = 2;
}
/*
///
/// Gets or sets the password iterations.
///
protected int PasswordIterations
{
get { return this.passwordIterations; }
set { this.passwordIterations = value; }
}
*/
#region "Basics"
///
/// Reversa el case de todas los caracteres.
///
///
/// El valor a reversar.
///
///
/// Cadena con los caracteres reversados. Tipo .
///
protected string ReverseCase(string value)
{
var result = Regex.Replace(
value,
"[a-zA-Z]",
m =>
char.IsUpper(m.Value[0]) ?
char.ToLower(m.Value[0]).ToString(CultureInfo.InvariantCulture) :
char.ToUpper(m.Value[0]).ToString(CultureInfo.InvariantCulture));
return result;
}
///
/// Generar el cifrado de los bytes existentes clave y el vector de inicialización.
///
///
/// La llave secreta.
///
///
/// Vector de inicialización.
///
///
/// Objeto de tipo .
///
protected ICryptoTransform GetEncryptor(byte[] secretKey, byte[] initializationVector)
{
// Create uninitialized Rijndael encryption object.
var symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Key size will be defined based on the number of the key bytes.
var encryptor = symmetricKey.CreateEncryptor(secretKey, initializationVector);
return encryptor;
}
///
/// Generar descifrador de los bytes existentes clave y el vector de inicialización.
///
///
/// La llave secreta.
///
///
/// Vector de inicialización.
///
///
/// Objeto de tipo .
///
protected ICryptoTransform GetDecryptor(byte[] secretKey, byte[] initializationVector)
{
// Create uninitialized Rijndael encryption object.
var symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Key size will be defined based on the number of the key bytes.
var encryptor = symmetricKey.CreateDecryptor(secretKey, initializationVector);
return encryptor;
}
#endregion
#region "Encription"
///
/// Método básico para codificación
///
///
/// Texto a codificar.
///
///
/// Objeto encriptador.
///
///
/// Cadena codificada. .
///
protected string Encriptador(string textToEncrypt, ICryptoTransform encryptor)
{
MemoryStream memoryStream = null;
CryptoStream cryptoStream = null;
if (string.IsNullOrEmpty(textToEncrypt))
{
throw new ArgumentNullException("textToEncrypt");
}
if (encryptor == null)
{
throw new ArgumentNullException("encryptor");
}
try
{
var textBytes = Encoding.UTF8.GetBytes(textToEncrypt);
memoryStream = new MemoryStream(textBytes.Length);
// Define cryptographic stream (always use Write mode for encryption).
cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(textBytes, 0, textBytes.Length); // Start encrypting.
cryptoStream.FlushFinalBlock(); // Finish encrypting.
var encriptedArray = memoryStream.ToArray();
memoryStream.Close(); // Close both streams.
cryptoStream.Close();
return Convert.ToBase64String(encriptedArray); // Convert encrypted data into a base64-encoded string.
}
catch (IOException)
{
if (memoryStream != null)
{
memoryStream.Close();
}
if (cryptoStream != null && cryptoStream.CanRead)
{
cryptoStream.Close();
}
throw;
}
}
///
/// Método básico para decodificación.
///
///
/// Texto a decodificar.
///
///
/// Objeto encriptador.
///
///
/// Cadena decodificada. .
///
protected string Desencriptador(string encryptedToText, ICryptoTransform decryptor)
{
MemoryStream memoryStream = null;
CryptoStream cryptoStream = null;
if (string.IsNullOrEmpty(encryptedToText))
{
throw new ArgumentNullException("encryptedToText");
}
if (decryptor == null)
{
throw new ArgumentNullException("decryptor");
}
try
{
var cipherTextBytes = Convert.FromBase64String(encryptedToText);
var plainTextBytes = new byte[cipherTextBytes.Length];
memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Write mode for encryption).
cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
// Start decrypting.
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close(); // Close both streams.
cryptoStream.Close();
// Convert decrypted data into a string.
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
catch (IOException)
{
if (memoryStream != null)
{
memoryStream.Close();
}
if (cryptoStream != null && cryptoStream.CanRead)
{
cryptoStream.Close();
}
throw;
}
}
#endregion
}
}