Simple C# encryption and decryption

There are various ways to encrypt and decrypt a string in with .Net. The simplest is to use Base64. But this just makes the string unreadable for a human, but it is not a real encryption. Although, for most case is is likely enough.

If you want something a little fancier, I have a simple solution for you:

 

public static String Encrypt(string source)
{
   
DESCryptoServiceProvider des = new DESCryptoServiceProvider
();
   
byte
[] Key = { 12, 13, 14, 15, 16, 17, 18, 19 };
   
byte
[] IV =  { 12, 13, 14, 15, 16, 17, 18, 19 };

    ICryptoTransform encryptor = des.CreateEncryptor(Key, IV);

    try
    {
       
byte[] IDToBytes = ASCIIEncoding
.ASCII.GetBytes(source);
       
byte
[] encryptedID = encryptor.TransformFinalBlock(IDToBytes, 0, IDToBytes.Length);
       
return Convert
.ToBase64String(encryptedID);
    }
   
catch (FormatException
)
    {
       
return null
;
    }
   
catch (Exception
)
    {
       
throw
;
    }
}


public static string Decrypt(string
encrypted)
{
   
byte
[] Key = { 12, 13, 14, 15, 16, 17, 18, 19 };
   
byte
[] IV =  { 12, 13, 14, 15, 16, 17, 18, 19 };

    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
   
ICryptoTransform
decryptor = des.CreateDecryptor(Key, IV);

    try
    {
       
byte[] encryptedIDToBytes = Convert
.FromBase64String(encrypted);
       
byte
[] IDToBytes = decryptor.TransformFinalBlock(encryptedIDToBytes, 0, encryptedIDToBytes.Length);
       
return ASCIIEncoding
.ASCII.GetString(IDToBytes);
    }
   
catch (FormatException
)
    {
       
return
null;
    }
   
catch (Exception
)
    {
       
throw
;
    }
}

Just make sure that you replace the Key and IV values.

I had to use the  Base64 Encoding in addition to the encryption so you can use the result string like a normal string and write it somewhere. Otherwise it could contain non ASCII characters and you couldn’t easily use it.

 

If you want to use the encrypted string in a url, you should HTML encode it too:

System.Web.HttpUtility.UrlEncode(Encrypt(mystring));
 

Have fun and let me know if you have any questions.




Ähnliche Beiträge


Leave a Reply

Your email address will not be published. Required fields are marked *



*