Quantcast
Channel: .NET – Kelly's Chronicles
Viewing all articles
Browse latest Browse all 48

Encryption and Decryption of strings with C#

$
0
0

Well I am checking out the Beale Street Historic District for the first time in Memphis, TN tonight. I have heard a lot about it since my arrival here so am excited to get to go. I think it will be fun.

Of course this would come up. I had written this previously in vb.net and I had the opportunity to use it again today. Of course in doing so, I discovered a bad coding practice violation I had committed. I had failed to return a value in my function’s Catch block of my code. C# doesn’t let you off the hook so easily and will bug you till you fix it. As noted previously, topic is encryption and decryption of strings. It is straightforward but you might find it useful. Simply pass in the string you want to encrypt/decrypt and the key you want to use.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class Crypto
{
    private static TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
    private static MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
    public static byte[] MD5Hash(string value)
    {
        return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value));
    }
    public static string Encrypt(string stringToEncrypt, string key)
    {
        DES.Key = Crypto.MD5Hash(key);
        DES.Mode = CipherMode.ECB;
        byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);
        return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
    }
    public static string Decrypt(string encryptedString, string key)
    {
        try
        {
            DES.Key = Crypto.MD5Hash(key);
            DES.Mode = CipherMode.ECB;
            byte[] Buffer = Convert.FromBase64String(encryptedString);
            return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
        }
        catch (Exception ex)
        {
            MessageBox.Show(“Invalid Key”, “Decryption Failed”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
// Inserted the following ‘return’ since all code paths must return a value in C#:
        return null;
    }
}

And now it’s usage…..

public class Form1
{
    private void Button1_Click(object sender, System.EventArgs e)
    {
        string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
        Label1.Text = Crypto.Encrypt(TextBox1.Text, key);
        TextBox1.Clear();
    }
    private void Button2_Click(object sender, System.EventArgs e)
    {
        string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
        TextBox1.Text = Crypto.Decrypt(Label1.Text, key);
    }

    }


Join me on Facebook



Viewing all articles
Browse latest Browse all 48

Latest Images

Trending Articles





Latest Images