none
Encrypt and Decrypt a String in c#

    Question

  • Hi,

    How to encrypt and decrypt a given string using any possible algorithm. I need the code in C#. Can someone pls help ?

    Thanks

    Thursday, July 12, 2012 11:30 AM

Answers

  • Hi, 

    Check with, 

    you can change these 

    static readonly string PasswordHash = "P@@Sw0rd";
    static readonly string SaltKey = "S@LT&KEY";
    static readonly string VIKey = "@1B2c3D4e5F6g7H8";

    for encrypt

    	public static string Encrypt(string plainText)
    		{
    			byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    
    			byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
    			var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
    			var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
    			
    			byte[] cipherTextBytes;
    
    			using (var memoryStream = new MemoryStream())
    			{
    				using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
    				{
    					cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
    					cryptoStream.FlushFinalBlock();
    					cipherTextBytes = memoryStream.ToArray();
    					cryptoStream.Close();
    				}
    				memoryStream.Close();
    			}
    			return Convert.ToBase64String(cipherTextBytes);
    		}

    to decrypt

    	public static string Decrypt(string encryptedText)
    		{
    			byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
    			byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
    			var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
    
    			var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
    			var memoryStream = new MemoryStream(cipherTextBytes);
    			var 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).TrimEnd("\0".ToCharArray());
    		}
    I hope this helps you...


    If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".

    Thursday, July 12, 2012 5:49 PM
  • Here is an encrption using popular RSA Alogorithm.

    public string EncryptString( string inputString, int dwKeySize, 
                                 string xmlString )
    {
            RSACryptoServiceProvider rsaCryptoServiceProvider = 
                                      new RSACryptoServiceProvider( dwKeySize );
        rsaCryptoServiceProvider.FromXmlString( xmlString );
        int keySize = dwKeySize / 8;
        byte[] bytes = Encoding.UTF32.GetBytes( inputString );
        RSACryptoServiceProvider here 
            int maxLength = keySize - 42;
        int dataLength = bytes.Length;
        int iterations = dataLength / maxLength;
        StringBuilder stringBuilder = new StringBuilder();
        for( int i = 0; i <= iterations; i++ )
        {
            byte[] tempBytes = new byte[ 
                    ( dataLength - maxLength * i > maxLength ) ? maxLength : 
                                                  dataLength - maxLength * i ];
            Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, 
                              tempBytes.Length );
            byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes,
                                                                      true );
                    stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
        }
        return stringBuilder.ToString();
    }
    public string DecryptString( string inputString, int dwKeySize, string xmlString )
    {
    RSACryptoServiceProvider rsaCryptoServiceProvider
                                 = new RSACryptoServiceProvider( dwKeySize );
        rsaCryptoServiceProvider.FromXmlString( xmlString );
        int base64BlockSize = ( ( dwKeySize / 8 ) % 3 != 0 ) ?
          ( ( ( dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ( ( dwKeySize / 8 ) / 3 ) * 4;
        int iterations = inputString.Length / base64BlockSize; 
        ArrayList arrayList = new ArrayList();
        for( int i = 0; i < iterations; i++ )
        {
            byte[] encryptedBytes = Convert.FromBase64String( 
                 inputString.Substring( base64BlockSize * i, base64BlockSize ) );
                    Array.Reverse( encryptedBytes );
            arrayList.AddRange( rsaCryptoServiceProvider.Decrypt( 
                                encryptedBytes, true ) );
        }
        return Encoding.UTF32.GetString( arrayList.ToArray( 
                                  Type.GetType( "System.Byte" ) ) as byte[] );
    }


    2) Here is one example in MSDN for md5

    static void Main(string[] args)
            {
                string source = "Hello World!";
                using (MD5 md5Hash = MD5.Create())
                {
                    string hash = GetMd5Hash(md5Hash, source);
                    Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");
                    Console.WriteLine("Verifying the hash...");
                    if (VerifyMd5Hash(md5Hash, source, hash))
                    {
                        Console.WriteLine("The hashes are the same.");
                    }
                    else
                    {
                        Console.WriteLine("The hashes are not same.");
                    }
                }
            }
            static string GetMd5Hash(MD5 md5Hash, string input)
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();
                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                // Return the hexadecimal string.
                return sBuilder.ToString();
            }
            // Verify a hash against a string.
            static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
            {
                // Hash the input.
                string hashOfInput = GetMd5Hash(md5Hash, input);
                // Create a StringComparer an compare the hashes.
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 == comparer.Compare(hashOfInput, hash))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

    • Edited by Srithar Thursday, July 12, 2012 12:54 PM
    • Proposed as answer by Srithar Thursday, July 12, 2012 12:55 PM
    • Marked as answer by Lisa ZhuModerator Monday, July 16, 2012 1:29 AM
    Thursday, July 12, 2012 12:51 PM
  • ----
    Thursday, July 12, 2012 1:29 PM

All replies

  • Look here:

    http://social.msdn.microsoft.com/Forums/sa/winformsapplications/thread/5aa93269-b0b0-48c3-941c-ade41f3e3f29

     

    Noam B.



    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...

    Thursday, July 12, 2012 11:41 AM
  • Here is an encrption using popular RSA Alogorithm.

    public string EncryptString( string inputString, int dwKeySize, 
                                 string xmlString )
    {
            RSACryptoServiceProvider rsaCryptoServiceProvider = 
                                      new RSACryptoServiceProvider( dwKeySize );
        rsaCryptoServiceProvider.FromXmlString( xmlString );
        int keySize = dwKeySize / 8;
        byte[] bytes = Encoding.UTF32.GetBytes( inputString );
        RSACryptoServiceProvider here 
            int maxLength = keySize - 42;
        int dataLength = bytes.Length;
        int iterations = dataLength / maxLength;
        StringBuilder stringBuilder = new StringBuilder();
        for( int i = 0; i <= iterations; i++ )
        {
            byte[] tempBytes = new byte[ 
                    ( dataLength - maxLength * i > maxLength ) ? maxLength : 
                                                  dataLength - maxLength * i ];
            Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, 
                              tempBytes.Length );
            byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes,
                                                                      true );
                    stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
        }
        return stringBuilder.ToString();
    }
    public string DecryptString( string inputString, int dwKeySize, string xmlString )
    {
    RSACryptoServiceProvider rsaCryptoServiceProvider
                                 = new RSACryptoServiceProvider( dwKeySize );
        rsaCryptoServiceProvider.FromXmlString( xmlString );
        int base64BlockSize = ( ( dwKeySize / 8 ) % 3 != 0 ) ?
          ( ( ( dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ( ( dwKeySize / 8 ) / 3 ) * 4;
        int iterations = inputString.Length / base64BlockSize; 
        ArrayList arrayList = new ArrayList();
        for( int i = 0; i < iterations; i++ )
        {
            byte[] encryptedBytes = Convert.FromBase64String( 
                 inputString.Substring( base64BlockSize * i, base64BlockSize ) );
                    Array.Reverse( encryptedBytes );
            arrayList.AddRange( rsaCryptoServiceProvider.Decrypt( 
                                encryptedBytes, true ) );
        }
        return Encoding.UTF32.GetString( arrayList.ToArray( 
                                  Type.GetType( "System.Byte" ) ) as byte[] );
    }


    2) Here is one example in MSDN for md5

    static void Main(string[] args)
            {
                string source = "Hello World!";
                using (MD5 md5Hash = MD5.Create())
                {
                    string hash = GetMd5Hash(md5Hash, source);
                    Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");
                    Console.WriteLine("Verifying the hash...");
                    if (VerifyMd5Hash(md5Hash, source, hash))
                    {
                        Console.WriteLine("The hashes are the same.");
                    }
                    else
                    {
                        Console.WriteLine("The hashes are not same.");
                    }
                }
            }
            static string GetMd5Hash(MD5 md5Hash, string input)
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();
                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                // Return the hexadecimal string.
                return sBuilder.ToString();
            }
            // Verify a hash against a string.
            static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
            {
                // Hash the input.
                string hashOfInput = GetMd5Hash(md5Hash, input);
                // Create a StringComparer an compare the hashes.
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 == comparer.Compare(hashOfInput, hash))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

    • Edited by Srithar Thursday, July 12, 2012 12:54 PM
    • Proposed as answer by Srithar Thursday, July 12, 2012 12:55 PM
    • Marked as answer by Lisa ZhuModerator Monday, July 16, 2012 1:29 AM
    Thursday, July 12, 2012 12:51 PM
  • ----
    Thursday, July 12, 2012 1:29 PM
  • Its simple, you can do like this:
    public static string Encrypt(string data)
    {
        TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
    
        DES.Mode = CipherMode.ECB;
        DES.Key = GetKey("a1!B78s!5(");
    
        DES.Padding = PaddingMode.PKCS7;
        ICryptoTransform DESEncrypt = DES.CreateEncryptor();
        Byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(data);
    
        return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
    }
    
    public static string Decrypt(string data)
    {
        TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
    
        DES.Mode = CipherMode.ECB;
        DES.Key = GetKey("a1!B78s!5(");
       
        DES.Padding = PaddingMode.PKCS7;
        ICryptoTransform DESEncrypt = DES.CreateDecryptor();
        Byte[] Buffer = Convert.FromBase64String(data.Replace(" ","+"));
    
        return Encoding.UTF8.GetString(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
    }
    And when you want call you make: Encrypt("blablablabla") or Decrypt("891bw01s13")
    • Edited by Norkk Thursday, July 12, 2012 1:41 PM
    Thursday, July 12, 2012 1:41 PM
  • Hi, 

    Check with, 

    you can change these 

    static readonly string PasswordHash = "P@@Sw0rd";
    static readonly string SaltKey = "S@LT&KEY";
    static readonly string VIKey = "@1B2c3D4e5F6g7H8";

    for encrypt

    	public static string Encrypt(string plainText)
    		{
    			byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    
    			byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
    			var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
    			var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
    			
    			byte[] cipherTextBytes;
    
    			using (var memoryStream = new MemoryStream())
    			{
    				using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
    				{
    					cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
    					cryptoStream.FlushFinalBlock();
    					cipherTextBytes = memoryStream.ToArray();
    					cryptoStream.Close();
    				}
    				memoryStream.Close();
    			}
    			return Convert.ToBase64String(cipherTextBytes);
    		}

    to decrypt

    	public static string Decrypt(string encryptedText)
    		{
    			byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
    			byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
    			var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
    
    			var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
    			var memoryStream = new MemoryStream(cipherTextBytes);
    			var 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).TrimEnd("\0".ToCharArray());
    		}
    I hope this helps you...


    If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".

    Thursday, July 12, 2012 5:49 PM
  • what is GetKey("...") actually calling when you do DES.Key.  There is not method in your code called GetKey.

    Friday, July 12, 2013 1:22 PM
  • @Kris444

    Great piece of code, I've used it in a messaging program across my network.
    What is this encryption method called? Like if I wanted to decrypt messages in another program, not written in C#, like on a Mac for example, how would I go about doing that?

    Thanks :D

    Wednesday, August 14, 2013 12:54 AM
  • There's a bug above in the EncryptString() function:  You need to comment out the line with:

    "RSACryptoServiceProvider here"

    This was inadvertently left behind as part of an earlier comment.

    Sunday, October 26, 2014 3:00 AM
  • Hi, can this be used for commercial use?

    Thanks

    Thursday, June 18, 2015 9:58 AM
  • found the missing peace here:

    http://stackoverflow.com/a/30187412/1411724


    Monday, November 21, 2016 1:47 PM
  • The encryption used here is how many bit encryption 

    Thursday, July 13, 2017 3:11 AM
  • I keep getting error saying in quotes "specified initialization vector (IV) does not match the block size for this algorithm." 

    Please help

    Thursday, July 13, 2017 3:17 AM
  • please, what algorithm or method that you had use in this encrypt, decrypt
    Friday, May 11, 2018 2:14 PM
  • Encrypt/Decrypt is different from encode/decode.

    You need passkey to encrypt/decrypt a message so only people who hold the key can get the original message, while you don't need one to encode/decode a message so anyone can get the original one.

    Btw, don't needlessly dig an old thread.


    Thursday, May 17, 2018 10:06 AM
    Answerer
  • I know that this is from 2012 but im getting an error on the GetKey, do you still have the metod?

    Thanks

    Wednesday, December 12, 2018 6:45 PM
  • You can use the below method.

    public static byte[] GetKey(string strKey)
            {
                byte[] Key = Convert.FromBase64String(strKey);
                return Key;
            }

    Tuesday, May 21, 2019 11:04 PM