using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.IO;
namespace Intranet
{
///
/// Criptografia Rijndael
///
public class Criptografia
{
public Criptografia()
{ }
///
/// Encriptação
///
/// Texto a encriptar
/// Texto encriptado
public static string Encriptar(string Texto)
{
string _chave = string.Empty;
SymmetricAlgorithm _algoritmo;
_algoritmo = new RijndaelManaged();
_algoritmo.Mode = CipherMode.CBC;
byte[] plainByte = Encoding.UTF8.GetBytes(Texto);
byte[] keyByte = Chave(_algoritmo, _chave);
// Seta a chave privada
_algoritmo.Key = keyByte;
_algoritmo.IV = new byte[] { 0xf, 0x6f, 0x13, 0x2e, 0x35, 0xc2, 0xcd, 0xf9, 0x5, 0x46, 0x9c, 0xea, 0xa8, 0x4b, 0x73, 0xcc };
// Interface de criptografia / Cria objeto de criptografia
ICryptoTransform cryptoTransform = _algoritmo.CreateEncryptor();
MemoryStream _memoryStream = new MemoryStream();
CryptoStream _cryptoStream = new CryptoStream(_memoryStream, cryptoTransform, CryptoStreamMode.Write);
// Grava os dados criptografados no MemoryStream
_cryptoStream.Write(plainByte, 0, plainByte.Length);
_cryptoStream.FlushFinalBlock();
// Busca o tamanho dos bytes encriptados
byte[] cryptoByte = _memoryStream.ToArray();
// Converte para a base 64 string para uso posterior em um xml
return Convert.ToBase64String(cryptoByte, 0, cryptoByte.GetLength(0));
}
///
/// Desencriptação
///
/// Texto a desencriptar
/// Texto desencriptado
public static string Desencriptar(string Texto)
{
string _chave = string.Empty;
SymmetricAlgorithm _algoritmo;
_algoritmo = new RijndaelManaged();
_algoritmo.Mode = CipherMode.CBC;
try
{
// Converte a base 64 string num array de bytes
byte[] cryptoByte = Convert.FromBase64String(Texto);
byte[] keyByte = Chave(_algoritmo, _chave);
// Seta a chave privada
_algoritmo.Key = keyByte;
_algoritmo.IV = new byte[] { 0xf, 0x6f, 0x13, 0x2e, 0x35, 0xc2, 0xcd, 0xf9, 0x5, 0x46, 0x9c, 0xea, 0xa8, 0x4b, 0x73, 0xcc };
// Interface de criptografia / Cria objeto de descriptografia
ICryptoTransform cryptoTransform = _algoritmo.CreateDecryptor();
try
{
MemoryStream _memoryStream = new MemoryStream(cryptoByte, 0, cryptoByte.Length);
CryptoStream _cryptoStream = new CryptoStream(_memoryStream, cryptoTransform, CryptoStreamMode.Read);
// Busca resultado do CryptoStream
StreamReader _streamReader = new StreamReader(_cryptoStream);
return _streamReader.ReadToEnd();
}
catch
{
return Texto; // Se der erro na desencriptação retorna o texto de origem
}
}
catch
{
return Texto; // Se der erro na desencriptação retorna o texto de origem
}
}
///
/// Criação da chave de encripatação
///
/// Chave de encripatação
private static byte[] Chave(SymmetricAlgorithm Algoritmo, string Chave)
{
string salt = string.Empty;
// Ajusta o tamanho da chave se necessário e retorna uma chave válida
if (Algoritmo.LegalKeySizes.Length > 0)
{
// Tamanho das chaves em bits
int keySize = Chave.Length * 8;
int minSize = Algoritmo.LegalKeySizes[0].MinSize;
int maxSize = Algoritmo.LegalKeySizes[0].MaxSize;
int skipSize = Algoritmo.LegalKeySizes[0].SkipSize;
if (keySize > maxSize)
{
// Valor máximo da chave
Chave = Chave.Substring(0, maxSize / 8);
}
else if (keySize < maxSize)
{
// Tamanho válido
int validSize = (keySize <= minSize) ? minSize : (keySize - keySize % skipSize) + skipSize;
if (keySize < validSize)
{
// Preenche a chave com arterisco para corrigir o tamanho
Chave = Chave.PadRight(validSize / 8, '*');
}
}
}
PasswordDeriveBytes key = new PasswordDeriveBytes(Chave, ASCIIEncoding.ASCII.GetBytes(salt));
return key.GetBytes(Chave.Length);
}
}
///
/// Criptografia DES
///
public class Criptografia_DES
{
public Criptografia_DES()
{
//
// TODO: Add constructor logic here
//
}
///
/// Encriptação
///
/// Texto a encriptar
/// Texto encriptado
public static string Encriptar(string Texto)
{
return Encrypt(Texto, WebConfigurationManager.AppSettings["CriptoDES"].ToString());
}
///
/// Desencriptação
///
/// Texto a desencriptar
/// Texto desencriptado
public static string Desencriptar(string Texto)
{
return Decrypt(Texto, WebConfigurationManager.AppSettings["CriptoDES"].ToString());
}
///
/// Encriptação DES
///
/// Texto a encriptar
/// Chave de encriptação
/// Texto encriptado
private static string Encrypt(string strText, string strEncrypt)
{
byte[] byKey = new byte[20];
byte[] dv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputArray = System.Text.Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, dv), CryptoStreamMode.Write);
cs.Write(inputArray, 0, inputArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
return ex.ToString();
}
}
///
/// Desencriptação DES
///
/// Texto a desencriptar
/// Chave de desencriptação
/// Texto desencriptado
private static string Decrypt(string strText, string strEncrypt)
{
byte[] bKey = new byte[20];
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
bKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
}