quinta-feira, 2 de julho de 2015

Cripto Util



using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Util
{
       ///
       /// Realiza a criptografia e descriptografia de uma frase.
       ///

       public class Criptografia
       {
             #region Atributos(variavéis)
             ///
             /// Frase secreta (chave)
             ///
             private string frase;
             ///
             /// Armazena a string que será criptografada
             ///

             private byte[] _IV;
             ///
             /// Armazena a string criptografada.
             ///
             private byte[] _Key;
             #endregion
            
             #region Propriedades(get/set)
             ///
             /// Frase Secreta
             ///
             private string Frase
             {
                    set
                    {
                           this.frase = value;
                           this.GerarChave(frase);
                    }
             }
             #endregion

             #region Construtores
             ///
             /// Inicia o Objeto
             ///

             public Criptografia()
             {
                    this.Frase = "minhafrase@secreta " ;
             }


             #endregion

             #region Metodos
             ///
             /// Criptografa o texto usando o algoritmo de Rijndael
             ///
             /// Texto a ser criptografado
             /// String criptografada

             public string Criptografar(string texto)
             {
                    if (texto != "")
                    {
                           // Cria objetos de criptografia
                           RijndaelManaged cryptoProvider = new RijndaelManaged();
                           MemoryStream ms = new MemoryStream();
                           CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(_Key, _IV), CryptoStreamMode.Write);
                           StreamWriter sw = new StreamWriter(cs);

                           sw.Write(texto);
                           sw.Flush();
                           cs.FlushFinalBlock();
                           ms.Flush();

                           // Converte bytes em string e retorna
                           return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
                    }
                    else
                           return "";
             }

      
             ///
             /// Descriptografa texto com algoritmo Rijndae
             ///

             /// String criptografada
             /// Texto
             public string Descriptografar(string texto)
             {
                    if (texto != "")
                    {                                                     
                           RijndaelManaged cryptoProvider = new RijndaelManaged();
                                                                                                                   
                           // Converte texto em matriz de bytes
                           byte[] buffer = Convert.FromBase64String(texto);
                           MemoryStream ms = new MemoryStream(buffer);
                           CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(_Key, _IV), CryptoStreamMode.Read);
                           StreamReader sr = new StreamReader(cs);

                           return sr.ReadToEnd();
                    }
                    else
                           return "";
             }

      
             ///
             /// Gera a chave de criptografia e o Vetor de Inicialização a partir da frase secreta
             ///
             /// Frase secreta
             private void GerarChave (string fraseSecreta)
             {
                    // Inicializa as variáveis com bytes
                    this._Key = new byte[24];
                    this._IV = new byte[16];

                    // Gera a chave de 32 bytes
                    byte[] bytePhrase = Encoding.ASCII.GetBytes(fraseSecreta);
                    SHA384Managed sha384 = new SHA384Managed();
                    sha384.ComputeHash(bytePhrase);
                    byte[] result = sha384.Hash;

                    // Passa os primeiros 24 bytes para a chave os outros 16 para o IV
                    for( int loop=0; loop<24 loop="" span="" style="color: blue;">this._Key[loop] = result[loop];
                    for( int loop=24; loop<40 loop="" span="" style="color: blue;">this._IV[loop-24] = result[loop];

                    sha384 = null;
             }
             #endregion
       }
}



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace DecryptorTester
{
    public partial class DecryptorTester : Form
    {       
        [DllImport("LapuinkaLibWin32.dll", CharSet = CharSet.Auto)]
        static extern void Decrypt(
            [MarshalAs(UnmanagedType.LPArray)] byte[] lpCryptedCode,
            [MarshalAs(UnmanagedType.LPArray)] byte[] lpDecryptedCode);

        public DecryptorTester()
        {
            InitializeComponent();
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            byte[] cryptedCodeByte = new System.Text.ASCIIEncoding().GetBytes(txtCode.Text);

            byte[] decryptedCodeByte = new byte[100];

            Decrypt(cryptedCodeByte, decryptedCodeByte);

            txtResult.Text = System.Text.Encoding.ASCII.GetString(decryptedCodeByte, 0, decryptedCodeByte.Length);
        }
     
        private void txtCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnDecrypt_Click(this, null);
            }
        }


Postar um comentário