CSharp examples for System.Security.Cryptography:DES
DES Encrypt Bytes
using System.IO;// w w w. ja v a2 s. c om using System.Security.Cryptography; using System.Text; using System; public class Main{ public static byte[] EncryptBytes(byte[] sourceBytes, byte[] keyBytes, byte[] keyIV) { if (sourceBytes == null || keyBytes == null || keyIV == null) { throw new ArgumentNullException("sourceBytes", "null"); } else { keyBytes = CheckByteArrayLength(keyBytes); keyIV = CheckByteArrayLength(keyIV); DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(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; } } }