DES Decrypt Bytes - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:DES

Description

DES Decrypt Bytes

Demo Code


using System.IO;//from  w  w w.java2s.  c om
using System.Security.Cryptography;
using System.Text;
using System;

public class Main{
        public static byte[] DecryptBytes(byte[] sourceBytes, byte[] keyBytes, byte[] keyIV)
        {
            if (sourceBytes == null || keyBytes == null || keyIV == null)
            {
                throw new ArgumentNullException("", "argument");
            }
            else
            {
                keyBytes = CheckByteArrayLength(keyBytes);
                keyIV = CheckByteArrayLength(keyIV);
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                cStream.Write(sourceBytes, 0, sourceBytes.Length);
                cStream.FlushFinalBlock();
                byte[] buffer = mStream.ToArray();
                mStream.Close();
                cStream.Close();
                return buffer;
            }
        }
        private static byte[] CheckByteArrayLength(byte[] byteArray)
        {
            byte[] resultBytes = new byte[8];
            if (byteArray.Length < 8)
            {
                return Encoding.UTF8.GetBytes("12345678");
            }
            else if (byteArray.Length % 8 != 0 || byteArray.Length > 64)
            {
                Array.Copy(byteArray, 0, resultBytes, 0, 8);
                return resultBytes;
            }
            else
            {
                return byteArray;
            }
        }
}

Related Tutorials