Click here to Skip to main content
15,916,398 members
Articles / Security / Encryption
Tip/Trick

Encrypt Strings with Passwords - AES 256 & SHA256

Rate me:
Please Sign up or sign in to vote.
4.95/5 (8 votes)
16 Nov 2016CPOL 91.1K   23   11
A simple class which allows to encrypt/decrypt a string with a password (AES/SHA2)

Introduction

Greetings from Germany! In this tip, I will show you a class that allows to encrypt and decrypt strings with a password.

Background

If you don't know what AES or SHA2 is, please read the wikipedia articles...

First, I create a hash with SHA2 (256 bit) from the password, this hash is the key and IV in the AES Encryption. The IV can only be 128 bit, so I just cut it to the right length.

You can only decrypt it if you have the password.

Using the Code

SecurityController.cs class code:

C#
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
 
namespace Encryption
{
  class SecurityController
  {
    public string Encrypt( string key, string data )
    {
      string encData = null;
      byte[][] keys = GetHashKeys(key);
 
      try
      {
        encData = EncryptStringToBytes_Aes( data, keys[0], keys[1] );
      }
      catch ( CryptographicException ) { }
      catch ( ArgumentNullException ) { }
 
      return encData;
    }
 
    public string Decrypt( string key, string data )
    {
      string decData = null;
      byte[][] keys = GetHashKeys(key);
 
      try
      {
        decData = DecryptStringFromBytes_Aes( data, keys[0], keys[1] );
      }
      catch ( CryptographicException ) { }
      catch ( ArgumentNullException ) { }
 
      return decData;
    }
 
    private byte[][] GetHashKeys( string key )
    {
      byte[][] result = new byte[2][];
      Encoding enc = Encoding.UTF8;
 
      SHA256 sha2 = new SHA256CryptoServiceProvider();
 
      byte[] rawKey = enc.GetBytes(key);
      byte[] rawIV = enc.GetBytes(key);
 
      byte[] hashKey = sha2.ComputeHash(rawKey);
      byte[] hashIV = sha2.ComputeHash(rawIV);
 
      Array.Resize( ref hashIV, 16 );
 
      result[0] = hashKey;
      result[1] = hashIV;
 
      return result;
    }
 
    //source: https://msdn.microsoft.com/de-de/library/system.security.cryptography.aes(v=vs.110).aspx
    private static string EncryptStringToBytes_Aes( string plainText, byte[] Key, byte[] IV )
    {
      if ( plainText == null || plainText.Length <= 0 )
        throw new ArgumentNullException( "plainText" );
      if ( Key == null || Key.Length <= 0 )
        throw new ArgumentNullException( "Key" );
      if ( IV == null || IV.Length <= 0 )
        throw new ArgumentNullException( "IV" );
 
      byte[] encrypted;
 
      using ( AesManaged aesAlg = new AesManaged() )
      {
        aesAlg.Key = Key;
        aesAlg.IV = IV;
 
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
 
        using ( MemoryStream msEncrypt = new MemoryStream() )
        {
          using ( CryptoStream csEncrypt = 
                  new CryptoStream( msEncrypt, encryptor, CryptoStreamMode.Write ) )
          {
            using ( StreamWriter swEncrypt = new StreamWriter( csEncrypt ) )
            {
              swEncrypt.Write( plainText );
            }
            encrypted = msEncrypt.ToArray();
          }
        }
      }
      return Convert.ToBase64String( encrypted );
    }
 
    //source: https://msdn.microsoft.com/de-de/library/system.security.cryptography.aes(v=vs.110).aspx
    private static string DecryptStringFromBytes_Aes( string cipherTextString, byte[] Key, byte[] IV )
    {
      byte[] cipherText = Convert.FromBase64String(cipherTextString);
 
      if ( cipherText == null || cipherText.Length <= 0 )
        throw new ArgumentNullException( "cipherText" );
      if ( Key == null || Key.Length <= 0 )
        throw new ArgumentNullException( "Key" );
      if ( IV == null || IV.Length <= 0 )
        throw new ArgumentNullException( "IV" );
 
      string plaintext = null;
 
      using ( Aes aesAlg = Aes.Create() )
      {
        aesAlg.Key = Key;
        aesAlg.IV = IV;
 
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
 
        using ( MemoryStream msDecrypt = new MemoryStream( cipherText ) )
        {
          using ( CryptoStream csDecrypt = 
                  new CryptoStream( msDecrypt, decryptor, CryptoStreamMode.Read ) )
          {
            using ( StreamReader srDecrypt = new StreamReader( csDecrypt ) )
            {
              plaintext = srDecrypt.ReadToEnd();
            }
          }
        }
      }
      return plaintext;
    }
  }
}

Example How To Use It

MainForm.cs class code:

C#
using System.Windows.Forms;
 
namespace Encryption
{
  public partial class MainForm : Form
  {
    private SecurityController _security;
 
    public MainForm()
    {
      InitializeComponent();
      _security = new SecurityController();
    }
 
    private void button_encrypt_Click( object sender, System.EventArgs e )
    {
      string password = textBox_password.Text;
      string notEncryptedText = textBox_text.Text;
      string encryptedText = _security.Encrypt( password, notEncryptedText );
 
      textBox_text.Text = encryptedText;
    }
 
    private void button_decrypt_Click( object sender, System.EventArgs e )
    {
      string password = textBox_password.Text;
      string encryptedText = textBox_text.Text;
      string notEncryptedText = _security.Decrypt( password, encryptedText );
 
      textBox_text.Text = notEncryptedText;
    }
  }
}

Before Encryption

After Encryption

After Decryption

Conclusion

I know it's very simple and not a lot of code, but if you don't know much about encryption and you need it, this class will help you a lot!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralIt is Easy to Crack if you have used the Hash as Public Key as it is in Bitcoin Wallet is a hash of private key! Pin
Serkan Ozkan 20226-Nov-22 6:05
Serkan Ozkan 20226-Nov-22 6:05 
QuestionHow to achieve same thing in java Pin
Vinothkumar Subramani10-Jul-20 1:34
Vinothkumar Subramani10-Jul-20 1:34 
GeneralMy vote of 5 Pin
raddevus9-Oct-19 5:30
mvaraddevus9-Oct-19 5:30 
QuestionHow to Decrypt the value using javascript Pin
Member 144847157-Jun-19 2:50
Member 144847157-Jun-19 2:50 
SuggestionBad Idea Pin
vbjay.net1-Mar-18 16:15
vbjay.net1-Mar-18 16:15 
PraiseMy vote of 5 Pin
sosplombierorleans21-Nov-16 6:27
sosplombierorleans21-Nov-16 6:27 
Generalexception handling issues Pin
sx200817-Nov-16 9:33
sx200817-Nov-16 9:33 
GeneralMy vote of 5 Pin
Farhad Reza17-Nov-16 4:26
Farhad Reza17-Nov-16 4:26 
QuestionCorrect practice? Pin
wvd_vegt16-Nov-16 22:58
professionalwvd_vegt16-Nov-16 22:58 
AnswerRe: Correct practice? Pin
APE-Germany16-Nov-16 23:37
APE-Germany16-Nov-16 23:37 
PraiseGood article Pin
JosephKelly9116-Nov-16 8:24
JosephKelly9116-Nov-16 8:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.