Products
Services
Contact Us

Scripts: C# :: Encryption :: Library Article #5

Developer's Section

Base 64 Encryption in C#
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (2046)
Favorites:

Learn how to create a class to encrypt and decrypt a string in C#

The Base 64 encryption class for C# is shown below:

 Code Snippet 1

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

/// <summary>
/// Summary description for Encryption64.
/// </summary>
public class Encryption64


  private byte[] key = {}; 
  private byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 }; 

  public string Decrypt(string stringToDecrypt, string sEncryptionKey) 
  { 
    byte[] inputByteArray = new byte[stringToDecrypt.Length]; 
    try 
    { 
      key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8)); 
      DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
      inputByteArray = Convert.FromBase64String(stringToDecrypt); 
      MemoryStream ms = new MemoryStream(); 
      CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), 
                                                        CryptoStreamMode.Write); 
      cs.Write(inputByteArray, 0, inputByteArray.Length); 
      cs.FlushFinalBlock(); 
      Encoding encoding=Encoding.UTF8; 
      return encoding.GetString(ms.ToArray()); 
    } 
    catch (Exception ex) 
    { 
      return ex.Message; 
    } 
  } 
  
  
  public string Encrypt(string stringToEncrypt,string sEncryptionKey) 
  { 
    try 
    { 
      key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8)); 
      DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
      Byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt); 
      MemoryStream ms = new MemoryStream(); 
      CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(key,IV),
                                                        CryptoStreamMode.Write); 
      cs.Write(inputByteArray,0,inputByteArray.Length); 
      cs.FlushFinalBlock(); 
      return Convert.ToBase64String(ms.ToArray()); 
    } 
    catch (Exception ex) 
    { 
      return ex.Message; 
    } 
  } 




Finally, we show you below how to use this class to encrypt/decrypt a string:

 Code Snippet 2

//to encrypt:
Encryption64  en62_1 = new Encryption64 ();
string myStringEncrypted = en62_1.Encrypt("this is string to be protected", "password123");  

//to decrypt:
Encryption64  en62_2 = new Encryption64 ();
string myStringEncrypted = en62_2.Decrypt(myStringEncrypted, "password123");  




See other Scripts in Encryption

Submit Your Scripts:


System Message:
  • Your C# script has been sent. Please allow 48 hours for processing.


If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]