TFS_ANTIGUO/SIGPC/wcfSigdd/Helper/Cryptography/CryptographyFoundation.cs

251 lines
8.2 KiB
C#
Raw Permalink Normal View History


namespace Helper
{
using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// Clase núcleo para la encriptación.
/// </summary>
public class CryptographyFoundation
{
/// <summary>
/// Cantidad de interacciones para contraseñas.
/// </summary>
private readonly int passwordIterations;
/// <summary>
/// Inicializa una nueva instancia de la clase <see cref="CryptographyFoundation"/>.
/// </summary>
protected CryptographyFoundation()
{
this.passwordIterations = 2;
}
/*
/// <summary>
/// Gets or sets the password iterations.
/// </summary>
protected int PasswordIterations
{
get { return this.passwordIterations; }
set { this.passwordIterations = value; }
}
*/
#region "Basics"
/// <summary>
/// Reversa el case de todas los caracteres.
/// </summary>
/// <param name="value">
/// El valor a reversar.
/// </param>
/// <returns>
/// Cadena con los caracteres reversados. Tipo <see cref="string"/>.
/// </returns>
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;
}
/// <summary>
/// Generar el cifrado de los bytes existentes clave y el vector de inicialización.
/// </summary>
/// <param name="secretKey">
/// La llave secreta.
/// </param>
/// <param name="initializationVector">
/// Vector de inicialización.
/// </param>
/// <returns>
/// Objeto de tipo <see cref="ICryptoTransform"/>.
/// </returns>
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;
}
/// <summary>
/// Generar descifrador de los bytes existentes clave y el vector de inicialización.
/// </summary>
/// <param name="secretKey">
/// La llave secreta.
/// </param>
/// <param name="initializationVector">
/// Vector de inicialización.
/// </param>
/// <returns>
/// Objeto de tipo <see cref="ICryptoTransform"/>.
/// </returns>
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"
/// <summary>
/// Método básico para codificación
/// </summary>
/// <param name="textToEncrypt">
/// Texto a codificar.
/// </param>
/// <param name="encryptor">
/// Objeto encriptador.
/// </param>
/// <returns>
/// Cadena codificada. <see cref="string"/>.
/// </returns>
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;
}
}
/// <summary>
/// Método básico para decodificación.
/// </summary>
/// <param name="encryptedToText">
/// Texto a decodificar.
/// </param>
/// <param name="decryptor">
/// Objeto encriptador.
/// </param>
/// <returns>
/// Cadena decodificada. <see cref="string"/>.
/// </returns>
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
}
}