• Home
  • Android
    • Apps
      • Android OS Build App
      • Compare Phone Contracts
        • Example 1
        • Example 2
        • Example 3
        • Example 4
        • Example 5
        • Example 6
      • Lump Sum Savings
  • Articles
  • Free Resources
    • Android Graphics Resources For Use In Apps
  • Index

Tekeye's Technology Blog

Encrypt Decrypt of a String in C# .NET

Articles - diana - April 20, 2015

C# Encryption and Decryption of a String With a Simple Function Call

Cryptography is a big subject area and extremely important for modern software and programs. If you are writing any type of software you need an understanding of software security and methods to keep data, code and users secure. Encrypting data keeps it secure because it hides its meaning, converting the plaintext (or cleartext) to ciphertext. To see the data again you need to decrypt the ciphertext back to plaintext. A simple example is the encryption of passwords to protect them from use by others.

Encryption and decryption of a password or other strings containing data can be done in many ways. There are many character substitution or transposition methods that pre-date the computing era and can be traced back to classical times. Modern computer based methods use symmetric key and asymmetric key mathematical algorithms. There are lots of well established algorithms from which to choose. However not everyone wants to take a course in cryptography just to be able to encrypt a string to hide some data and decrypt it back again. That’s where this example C# encryption and decryption code comes in handy. This code was tested in Visual Studio 2013.

This C# code has been boiled down to an encryption function that takes a plaintext string and passphrase and returns an encrypted string. There is the reverse function that takes the ciphertext and the passphrase and returns the plaintext. This is a quick and easy method of adding some encryption to a C# project, or any .NET project. The encrypt decrypt C# string functions are in a simple class. An example project shows how simple it is to use them.

The code presented here is not going to be explained in detail. Instead it is recommended that it is studied. The reader should to refer to online resources and the Microsoft .NET Framework documentation on the System.Security.Cryptography namespace. The code was picked up from the Stack Overflow question Encrypting and Decrypting a String in C#.

This code is using a symmetric key algorithm known as Rijndael (after the inventors Vincent Rijmen and Joan Daemen) implemented by the .NET Framework. This algorithm performs substitutions and permutations on data blocks with keys sized in multiples of 32 bits. The cipher mode is Cipher Block Chaining (CBC) which can take a different Initialisation Vector (IV) for each use to further obfuscate the cipher text. In which case the same passphrase and plaintext will produce different ciphertexts if a different IV is used. Change the IV string for you own value or generate a random one (this can be done at https://www.random.org/strings/).  The passphrase is not salted but can be, see the documentation for PasswordDeriveBytes. Note that the encryption and decryption is performed on bytes and not Unicode characters hence the conversion from strings to byte arrays in the code (it also means that these functions can be adapted for other data types if required).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//Don’t forget the using System.Security.Cryptography; statement wher you add this class
public static class Encrypt
{
    // This size of the IV (in bytes) must = (keysize / 8).  Default keysize is 256, so the IV must be
    // 32 bytes long.  Using a 16 character string here gives us 32 bytes when converted to a byte array.
    private const string initVector = “pemgail9uzpgzl88”;
    // This constant is used to determine the keysize of the encryption algorithm
    private const int keysize = 256;
    //Encrypt
    public static string EncryptString(string plainText, string passPhrase)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        return Convert.ToBase64String(cipherTextBytes);
    }
    //Decrypt
    public static string DecryptString(string cipherText, string passPhrase)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
    }
}

This small example shows the encrypt decrypt functionality in action. Create a similar WinForm or download the code, which has this dialog.

Encrypt Decrypt a C# String

Encryption of a string in C# with a password is as simple as:

1
textBoxEncrypted.Text = Encrypt.EncryptString(textBoxString.Text, textBoxPassword.Text);

And decryption is just as easy:

1
textBoxString.Text = Encrypt.DecryptString(textBoxEncrypted.Text, textBoxPassword.Text);

Example project and source code: EncryptString.zip

See also: Effortless .NET Encryption

This entry was posted in Computing and tagged .NET, C#, Cryptography, Decryption, Encryption, programming, Visual Studio by Tek Eye. Bookmark the permalink.

Related posts:

  1. Show PHP Settings with phpinfo and Example PHP $_SERVER Display Page
  2. Responsive Menu Tutorial for HTML Web Pages, No JQuery
  3. Upgrade PHP for CentOS 6 Using Additional Repositories
  4. Unzip File on VPS? How to Extract a Zip File on a Linux VPS
 0 0

Share This Post!

About Author / diana

No Comment

Leave a Reply Cancel Reply

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

Previous Post
Next Post

About Me

Thanks for visits my website, hope you like my posts

Recent Posts

  • How To Control Your Mac With Your iPhone From Anywhere
  • How To Solve Windows System Crashes
  • Working on the Run: Tablet or Laptop?
  • Simple Copywriting System
  • Best Mod Apk Games Market
  • Data Recovery and the Three Golden Backups
  • Responsive Menu Tutorial for HTML Web Pages, No JQuery
  • Show PHP Settings with phpinfo and Example PHP $_SERVER Display Page
  • Upgrade PHP for CentOS 6 Using Additional Repositories
  • Unzip File on VPS? How to Extract a Zip File on a Linux VPS
  • Encrypt Decrypt of a String in C# .NET
  • WebMatrix Rename Site and Changing Virtual Folder Name
  • PHP on Windows Using WebMatrix Single Click Install
  • Develop a Website on Windows Using Microsoft WebMatrix
  • CentOS 6 to CentOS 7 Upgrade Using Red Hat Upgrade Tool

Archives

  • January 2021
  • January 2016
  • June 2015
  • April 2015
  • March 2015
  • February 2015
  • January 2015

Widget Area 1

Assign a Widget

Widget Area 2

Assign a Widget

Widget Area 3

Assign a Widget

Alison is a creative soft blog theme made with by angrygorilla.