Decrypt String with encryption Key - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:Encrypt Decrypt

Description

Decrypt String with encryption Key

Demo Code


using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.IO;/*from w  w  w  .j  a  va2  s  .c  o  m*/
using System.Collections.Generic;
using System;

public class Main{
        public static string Decrypt(string text, string encryptionKey)
        {
            // Check for valid length encryption key 
            if (encryptionKey.Length < 8)
            {
                throw new Exception("Encryption Key must be a minimum of 8 characters long");
            }

            if (text.Trim().Length == 0)
            {
                return string.Empty;
            }

            var inputByteArray = new byte[text.Length + 1];

            // We are going to make things easy by insisting on an 8 byte legal key length
            CryptographyHelper.Key = System.Text.Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8));
            var des = new DESCryptoServiceProvider();

            // We have a base 64 encoded string so first must decode to regular unencoded (encrypted) string
            inputByteArray = Convert.FromBase64String(text);

            // Now decrypt the regular string
            var ms = new MemoryStream();

            var cs = new CryptoStream(ms, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(ms.ToArray());
        }
}

Related Tutorials